🤯 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
✨ feat(heterogeneous-agent): add Codex desktop integration (#14067)
Arvin Xu82096dcd89c9
diff --git a/.agents/skills/heterogeneous-agent/SKILL.md b/.agents/skills/heterogeneous-agent/SKILL.mdnew file mode 100644index 00000000000..7d7be23f6e6--- /dev/null+++ b/.agents/skills/heterogeneous-agent/SKILL.md@@ -0,0 +1,83 @@+---+name: heterogeneous-agent+description: Guide for implementing and debugging LobeHub heterogeneous agent integrations such as Claude Code, Codex, and future external CLI agents. Use when working on adapter event mapping, Electron IPC transport, renderer persistence, tool-call chaining, subagent threads, resume/session handling, or regressions like mixed multi-tool messages, broken step boundaries, stuck tool loading, and orphan tool messages. Triggers on 'heterogeneous agent', 'hetero agent', '异构 agent', 'claude code adapter', 'codex adapter', 'external agent CLI', '孤立 tool 消息', 'raw Codex trace', or adapter/executor bugs.+---++# Heterogeneous Agent Development++Use this skill when the bug or feature lives in the external CLI agent pipeline, not the normal server-side agent runtime.++## Use This Skill For++- Adding or changing a driver under `apps/desktop/src/main/modules/heterogeneousAgent/drivers/`+- Editing an adapter under `packages/heterogeneous-agents/src/adapters/`+- Debugging `heteroAgentRawLine` transport, `window.__HETERO_AGENT_TRACE`, or `executeHeterogeneousAgent`+- Fixing Claude Code stream-json bugs such as duplicate partial/full chunks, broken `message.id` boundaries, missing `tool_result`, TodoWrite state drift, or subagent thread routing+- Fixing Codex JSONL bugs such as mixed multi-tool messages, broken turn boundaries, or missing tool-result mapping+- Fixing step-boundary, tool persistence, subagent thread, or resume bugs in Claude Code / Codex flows+- Reproducing multi-tool mixing, orphan tool messages, or stuck tool-result loading++## Pipeline Map++1. CLI raw stdout / JSONL+2. Electron main spawns the CLI and broadcasts `heteroAgentRawLine`+3. Adapter maps raw provider events into `HeterogeneousAgentEvent`+4. `executeHeterogeneousAgent` persists assistant/tool messages and forwards stream events+5. `createGatewayEventHandler` hydrates the UI+6. Only after this path looks correct should you move on to `agent-tracing` or context-engine debugging++## Read These Files First++- `apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts`+- `apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts`+- `apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts`+- `packages/heterogeneous-agents/src/adapters/claudeCode.ts`+- `packages/heterogeneous-agents/src/adapters/codex.ts`+- `src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts`+- `src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts`++## Default Debug Order++1. Prove whether the raw CLI output is correct before touching UI code.+2. If raw output is correct, compare it with adapter output. In dev, `executeHeterogeneousAgent` exposes `window.__HETERO_AGENT_TRACE`.+3. If adapted events look correct, inspect `persistToolBatch`, `persistToolResult`, step transitions, and subagent routing.+4. Turn the repro into a focused test before fixing.+5. Only after the transport/adapter/executor path looks sound should you debug later-stage message processing.++## Critical Invariants++- One raw tool item must map to one stable `ToolCallPayload.id`.+- A new main-agent step must emit a boundary signal before events are forwarded to the new assistant.+- In Claude Code, multiple assistant events with the same `message.id` are one turn, not multiple turns.+- In Claude Code, `tool_result` lives in `type: 'user'` events, not assistant events.+- In Claude Code partial mode, `message_delta.usage` is authoritative; do not trust echoed usage on every assistant block.+- `persistToolBatch` must pre-register assistant `tools[]` before creating tool messages.+- Every tool message must keep `parentId` equal to the owning assistant and `tool_call_id` equal to the tool id.+- `tool_result` must resolve an existing `toolMsgIdByCallId`.+- Subagent chunks must stay in thread scope and must not be forwarded into the main assistant stream.+- Never clear the global `toolMsgIdByCallId` map at main step boundaries.++## Common Bug Patterns++- Claude Code duplicates text or thinking:+ check whether partial deltas and the later full assistant block are both being emitted.+- Claude Code opens too many assistant messages:+ check whether the adapter is cutting steps on every assistant event instead of only on `message.id` changes.+- Claude Code tool results never land:+ check whether `type: 'user'` `tool_result` blocks are being ignored because the code only inspects assistant events.+- Claude Code TodoWrite cards look stale:+ check whether synthesized `pluginState.todos` is being attached at tool-result time.+- Claude Code subagent transcript leaks into the main bubble:+ check `parent_tool_use_id` handling and whether subagent chunks are being forwarded to the main gateway handler.+- Multiple Codex tools collapse into one assistant message:+ first check whether the adapter emits a usable step boundary such as `newStep` or an equivalent turn-change signal.+- Orphan tool messages:+ first check step-transition ordering and whether `persistToolBatch` Phase 1 ran before tool message creation.+- Tool bubble stays loading:+ look for `tool_result for unknown toolCallId` and missing `result_msg_id` backfill.+- Subagent tools show up in the main bubble:+ check for subagent chunks reaching the main gateway handler.++## References++- For commands, trace capture, invariants, and focused test commands, read [references/debug-workflow.md](./references/debug-workflow.md).diff --git a/.agents/skills/heterogeneous-agent/references/debug-workflow.md b/.agents/skills/heterogeneous-agent/references/debug-workflow.mdnew file mode 100644index 00000000000..85e3ea51367--- /dev/null+++ b/.agents/skills/heterogeneous-agent/references/debug-workflow.md@@ -0,0 +1,246 @@+# Heterogeneous Agent Debug Workflow++## Contents++1. Pipeline map+2. Capture raw CLI traces first+3. Compare raw and adapted events+4. Check step boundaries before persistence+5. Check tool persistence invariants+6. Focused tests+7. Repro-to-fix workflow++## 1. Pipeline Map++```+CLI raw stdout+ -> HeterogeneousAgentCtr (Electron main)+ -> heteroAgentRawLine broadcast+ -> createAdapter(...)+ -> executeHeterogeneousAgent(...)+ -> persistToolBatch / persistToolResult+ -> createGatewayEventHandler(...)+ -> UI hydration+```++Start at the leftmost broken layer. Do not jump straight to UI rendering unless raw and adapted events already look correct.++## 2. Capture Raw CLI Traces First++### Codex raw JSONL++Use a read-only prompt and save traces under the repo-local scratch directory `.heerogeneous-tracing/`.++```bash+ts=$(date +%Y%m%d-%H%M%S)+out=".heerogeneous-tracing/codex-${ts}.jsonl"+last=".heerogeneous-tracing/codex-${ts}.last.txt"++cat << 'EOF' | codex exec --json --skip-git-repo-check --sandbox read-only -C "$PWD" -o "$last" - > "$out"+You are being run only to collect a raw Codex JSON event trace.+Do not modify any files.+Use at least 4 separate shell tool invocations, one invocation per command.+Run a short sequence of read-only repo checks and then reply with a one-sentence summary.+EOF+```++What to look for in the JSONL:++- `thread.started`+- `turn.started`+- `item.started` / `item.completed`+- `item.type === 'command_execution'`+- `item.type === 'agent_message'`+- `turn.completed`++If raw Codex already merges tools into one item, the adapter is innocent. If raw Codex emits independent items but UI collapses them, the bug is downstream.++If the repo already contains useful traces under `.heerogeneous-tracing/`, inspect them before reproducing.++### Claude Code raw NDJSON++Mirror the arguments from `apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts`.++- `-p`+- `--input-format stream-json`+- `--output-format stream-json`+- `--verbose`+- `--include-partial-messages`+- `--permission-mode bypassPermissions`++You can capture a local raw trace like this:++```bash+ts=$(date +%Y%m%d-%H%M%S)+out=".heerogeneous-tracing/claude-${ts}.ndjson"++cat << 'EOF' | claude -p \+ --input-format stream-json \+ --output-format stream-json \+ --verbose \+ --include-partial-messages \+ --permission-mode bypassPermissions \+ > "$out"+{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Do a few read-only repo checks, use several tool calls, and then summarize briefly."}]}}+EOF+```++What to look for in Claude Code raw traces:++- `type: 'system', subtype: 'init'`+- `type: 'assistant'` blocks for `thinking`, `tool_use`, and `text`+- `type: 'user'` blocks containing `tool_result`+- `type: 'stream_event'` with `message_start`, `content_block_delta`, and `message_delta`+- `type: 'result'`+- `type: 'rate_limit_event'`++Important Claude Code semantics:++- Each content block often arrives as its own assistant event.+- Multiple assistant events can share the same `message.id`; that is still one turn.+- `message.id` change is the main-step boundary.+- Partial deltas arrive before the later full assistant block.+- `message_delta.usage` is the authoritative per-turn usage.+- Subagent events are tagged with `parent_tool_use_id`.++If the repo already contains useful references, inspect these first:++- `.heerogeneous-tracing/cc-monitor-real-trace.jsonl`+- `.heerogeneous-tracing/cc-stream-chain-reference.md`++If you only need boundary semantics or tool persistence behavior, prefer existing adapter tests under:++- `packages/heterogeneous-agents/src/adapters/claudeCode.test.ts`+- `packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts`++## 3. Compare Raw And Adapted Events++In dev builds, `executeHeterogeneousAgent` stores raw lines plus adapted events on:++- `window.__HETERO_AGENT_TRACE`++Use that trace to compare:++- raw `item.started` / `item.completed`+- adapted `stream_chunk { chunkType: 'tools_calling' }`+- adapted `tool_result`+- adapted `tool_end`++For Codex, the usual mapping is:++- raw `item.started(command_execution)` -> `tools_calling` + `tool_start`+- raw `item.completed(command_execution)` -> `tool_result` + `tool_end`+- raw `item.completed(agent_message)` -> `stream_chunk(text)`++If the raw trace is right but adapted events are wrong, fix the adapter before touching persistence.++## 4. Check Step Boundaries Before Persistence++This is the first thing to verify for "mixed tools in one assistant" bugs.++### Claude Code++Claude Code step boundaries are keyed off assistant `message.id` changes. The adapter should emit:++- `stream_end`+- `stream_start { newStep: true }`++Also verify these Claude-specific invariants:++- the first assistant after init does not open a new step+- repeated assistant events with the same `message.id` do not open a new step+- partial `content_block_delta` text/thinking does not get duplicated by the later full assistant event+- `tool_result` from `type: 'user'` updates the matching tool row+- `parent_tool_use_id` creates thread-scoped subagent chunks instead of main-stream chunks+- TodoWrite `tool_use.input` is converted into synthesized `pluginState.todos` on `tool_result`++Good references:++- `packages/heterogeneous-agents/src/adapters/claudeCode.ts`+- `packages/heterogeneous-agents/src/adapters/claudeCode.test.ts`++### Codex++Codex raw traces usually provide turn-level boundaries through:++- `turn.started`+- `turn.completed`++The executor only cuts a new assistant message when it receives a step-boundary signal it understands. If the adapter emits `stream_start` without `newStep`, multiple Codex tools and text chunks can accumulate under the same assistant longer than intended.++Relevant files:++- `packages/heterogeneous-agents/src/adapters/codex.ts`+- `src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts`++## 5. Check Tool Persistence Invariants++Read `persistToolBatch` and `persistToolResult` before changing UI code.++### `persistToolBatch`++The expected order is:++1. Pre-register assistant `tools[]`+2. Create `role: 'tool'` messages+3. Backfill `result_msg_id` onto assistant `tools[]`++If tool rows are created before assistant `tools[]` are registered, orphan tool messages are likely.++### `persistToolResult`++`tool_result` must resolve the tool row through `toolMsgIdByCallId`.++Warning signs:++- `tool_result for unknown toolCallId`+- tool rows with empty content forever+- missing `result_msg_id`++For Claude Code, remember that tool results originate from raw `type: 'user'` events.++### Main vs subagent scope++- Main-agent tool state is per-step.+- `toolMsgIdByCallId` is global across main and subagent scopes.+- Subagent chunks must not be forwarded into the main gateway handler.++If subagent events leak to the main handler, the main bubble can inherit the wrong `tools[]` and content.++## 6. Focused Tests++Run the smallest useful test set first.++```bash+bunx vitest run --silent='passed-only' 'packages/heterogeneous-agents/src/adapters/codex.test.ts'+bunx vitest run --silent='passed-only' 'packages/heterogeneous-agents/src/adapters/claudeCode.test.ts'+bunx vitest run --silent='passed-only' 'src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts'+```++Especially useful places:++- `packages/heterogeneous-agents/src/adapters/codex.test.ts`+- `packages/heterogeneous-agents/src/adapters/claudeCode.test.ts`+- `src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts`++Claude Code-specific assertions worth adding when fixing bugs:++- same `message.id` does not emit `newStep`+- changed `message.id` does emit `stream_end` plus `stream_start { newStep: true }`+- partial text/thinking is emitted once+- `tool_result` from `user` events reaches the right tool row+- subagent chunks carry `subagent.parentToolCallId`+- TodoWrite result synthesizes `pluginState.todos`++When the bug comes from a real trace, distill it into the closest existing test file instead of relying on manual UI-only repros.++## 7. Repro-To-Fix Workflow++1. Capture a raw trace and save it under `.heerogeneous-tracing/`.+2. Confirm whether the bug appears in raw events, adapted events, or persistence.+3. Add or update the narrowest failing test near the broken layer.+4. Fix the smallest layer that can explain the symptom.+5. Re-run focused tests.+6. Only then do an Electron smoke test with the `local-testing` skill if UI confirmation is still needed.++Do not start with a broad Electron repro if a raw trace or adapter test can prove the fault zone faster.diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.tsindex a9845aefc4d..9b4a1c78675 100644--- a/apps/desktop/electron.vite.config.ts+++ b/apps/desktop/electron.vite.config.ts@@ -188,6 +188,7 @@ export default defineConfig({],resolve: {dedupe: ['react', 'react-dom'],+ tsconfigPaths: true,},},});diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 104ac6262e2..25b46bc21ca 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -1,53 +1,56 @@import type { ChildProcess } from 'node:child_process';import { spawn } from 'node:child_process';import { createHash, randomUUID } from 'node:crypto';-import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { access, mkdir, readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import type { Readable, Writable } from 'node:stream';+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import {+ CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ CODEX_CLI_INSTALL_COMMANDS,+ CODEX_CLI_INSTALL_DOCS_URL,+ HeterogeneousAgentSessionErrorCode,+} from '@lobechat/electron-client-ipc';import { app as electronApp, BrowserWindow } from 'electron';+import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';+import type {+ HeterogeneousAgentImageAttachment,+ HeterogeneousAgentParsedOutput,+} from '@/modules/heterogeneousAgent/types';import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';+import { detectHeterogeneousCliCommand } from '@/modules/toolDetectors';import { createLogger } from '@/utils/logger';import { ControllerModule, IpcMethod } from './index';const logger = createLogger('controllers:HeterogeneousAgentCtr');+const CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS = [+ /no conversation found/i,+ /thread .*not found/i,+ /conversation .*not found/i,+ /resume.*not found/i,+] as const;+const CLI_AUTH_REQUIRED_PATTERNS = [+ /failed to authenticate/i,+ /invalid authentication credentials/i,+ /authentication[_ ]error/i,+ /not authenticated/i,+ /\bunauthorized\b/i,+ /\b401\b/,+] as const;+const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [+ /working directory/i,+ /\bcwd\b/i,+ /different directory/i,+ /directory.*mismatch/i,+] as const;/** Directory under appStoragePath for caching downloaded files */const FILE_CACHE_DIR = 'heteroAgent/files';-// ─── CLI presets per agent type ───-// Mirrors @lobechat/heterogeneous-agents/registry but runs in main process-// (can't import from the workspace package in Electron main directly)--interface CLIPreset {- baseArgs: string[];- promptMode: 'positional' | 'stdin';- resumeArgs?: (sessionId: string) => string[];-}--const CLI_PRESETS: Record<string, CLIPreset> = {- 'claude-code': {- baseArgs: [- '-p',- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--verbose',- '--include-partial-messages',- '--permission-mode',- 'bypassPermissions',- ],- promptMode: 'stdin',- resumeArgs: (sid) => ['--resume', sid],- },- // Future presets:- // 'codex': { baseArgs: [...], promptMode: 'positional' },- // 'kimi-cli': { baseArgs: [...], promptMode: 'positional' },-};-// ─── IPC types ───interface StartSessionParams {@@ -69,14 +72,9 @@ interface StartSessionResult {sessionId: string;}-interface ImageAttachment {- id: string;- url: string;-}-interface SendPromptParams {/** Image attachments to include in the prompt (downloaded from url, cached by id) */- imageList?: ImageAttachment[];+ imageList?: HeterogeneousAgentImageAttachment[];prompt: string;sessionId: string;}@@ -115,15 +113,19 @@ interface AgentSession {cwd?: string;env?: Record<string, string>;process?: ChildProcess;+ resumeSessionId?: string;sessionId: string;}+type SessionErrorPayload = HeterogeneousAgentSessionError | string;+/*** External Agent Controller — manages external agent CLI processes via Electron IPC.*- * Agent-agnostic: uses CLI presets from a registry to support Claude Code,- * Codex, Kimi CLI, etc. Only handles process lifecycle and raw stdout line- * broadcasting. All event parsing and DB persistence happens on the Renderer side.+ * Agent-agnostic: delegates spawn-plan construction and stdout framing to a+ * per-agent driver so Claude Code, Codex, and future CLIs can differ in+ * prompt transport, resume semantics, and raw stream shape without turning+ * this controller into a giant `switch`.** Lifecycle: startSession → sendPrompt → (heteroAgentRawLine broadcasts) → stopSession*/@@ -132,6 +134,203 @@ export default class HeterogeneousAgentCtr extends ControllerModule {private sessions = new Map<string, AgentSession>();+ private resolveSessionCommand(session: AgentSession): string {+ const resolvedCommand = session.command.trim();+ if (resolvedCommand) return resolvedCommand;++ return session.agentType === 'codex' ? 'codex' : 'claude';+ }++ private buildCodexCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {+ const command = this.resolveSessionCommand(session);++ return {+ agentType: 'codex',+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ command,+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,+ installCommands: CODEX_CLI_INSTALL_COMMANDS,+ message: `Codex CLI was not found. Install it and make sure \`${command}\` can be executed.`,+ };+ }++ private buildClaudeCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {+ const command = this.resolveSessionCommand(session);++ return {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ command,+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ message: `Claude Code CLI was not found. Install it and make sure \`${command}\` can be executed.`,+ };+ }++ private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {+ switch (session.agentType) {+ case 'claude-code': {+ return this.buildClaudeCodeCliMissingError(session);+ }+ case 'codex': {+ return this.buildCodexCliMissingError(session);+ }+ default: {+ return;+ }+ }+ }++ private buildCliAuthRequiredError(+ session: AgentSession,+ stderr: string,+ ): HeterogeneousAgentSessionError | undefined {+ const command = this.resolveSessionCommand(session);++ switch (session.agentType) {+ case 'claude-code': {+ return {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ command,+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr,+ };+ }+ case 'codex': {+ return {+ agentType: 'codex',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ command,+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,+ message:+ 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr,+ };+ }+ default: {+ return;+ }+ }+ }++ private getErrorMessage(error: unknown): string | undefined {+ return typeof error === 'string'+ ? error+ : error instanceof Error+ ? error.message+ : typeof error === 'object' &&+ error &&+ 'message' in error &&+ typeof error.message === 'string'+ ? error.message+ : undefined;+ }++ private buildCodexResumeError(+ code:+ | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch+ | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ stderr: string,+ session: AgentSession,+ ): HeterogeneousAgentSessionError {+ const message =+ code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch+ ? 'The saved Codex thread can only be resumed from its original working directory.'+ : 'The saved Codex thread could not be found, so it can no longer be resumed.';++ return {+ agentType: 'codex',+ code,+ command: session.command,+ message,+ resumeSessionId: session.resumeSessionId,+ stderr,+ workingDirectory: session.cwd,+ };+ }++ private getCodexResumeError(+ error: unknown,+ session: AgentSession,+ ): HeterogeneousAgentSessionError | undefined {+ if (session.agentType !== 'codex' || !session.resumeSessionId) return;++ const message = this.getErrorMessage(error);++ if (!message) return;++ if (CODEX_RESUME_CWD_MISMATCH_PATTERNS.some((pattern) => pattern.test(message))) {+ return this.buildCodexResumeError(+ HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch,+ message,+ session,+ );+ }++ if (CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(message))) {+ return this.buildCodexResumeError(+ HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ message,+ session,+ );+ }+ }++ private getCliAuthRequiredError(+ error: unknown,+ session: AgentSession,+ ): HeterogeneousAgentSessionError | undefined {+ const message = this.getErrorMessage(error);++ if (!message || !CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(message))) return;++ return this.buildCliAuthRequiredError(session, message);+ }++ private getSessionErrorPayload(error: unknown, session: AgentSession): SessionErrorPayload {+ if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {+ const cliMissingError = this.buildCliMissingError(session);+ if (cliMissingError) return cliMissingError;+ }++ const resumeError = this.getCodexResumeError(error, session);+ if (resumeError) return resumeError;++ const authRequiredError = this.getCliAuthRequiredError(error, session);+ if (authRequiredError) return authRequiredError;++ return error instanceof Error ? error.message : String(error);+ }++ private async getSpawnPreflightError(+ session: AgentSession,+ ): Promise<HeterogeneousAgentSessionError | undefined> {+ const defaultCommand =+ session.agentType === 'claude-code'+ ? 'claude'+ : session.agentType === 'codex'+ ? 'codex'+ : undefined;+ if (!defaultCommand) return;++ const command = this.resolveSessionCommand(session);+ const status =+ command === defaultCommand+ ? await this.app.toolDetectorManager?.detect?.(defaultCommand, true)+ : await detectHeterogeneousCliCommand(+ session.agentType === 'claude-code' ? 'claude-code' : 'codex',+ command,+ );+ const cliMissingError = this.buildCliMissingError(session);++ if (!status || status.available || !cliMissingError) return;++ return cliMissingError;+ }+// ─── Broadcast ───private broadcast<T>(channel: string, data: T) {@@ -164,7 +363,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {* Download an image by URL, with local disk cache keyed by id.*/private async resolveImage(- image: ImageAttachment,+ image: HeterogeneousAgentImageAttachment,): Promise<{ buffer: Buffer; mimeType: string }> {const cacheDir = this.fileCacheDir;const cacheKey = this.getImageCacheKey(image.id);@@ -201,12 +400,71 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return { buffer, mimeType };}+ private guessImageExtension(+ mimeType: string,+ image: HeterogeneousAgentImageAttachment,+ ): string | undefined {+ const knownByMime: Record<string, string> = {+ 'image/gif': '.gif',+ 'image/jpeg': '.jpg',+ 'image/png': '.png',+ 'image/webp': '.webp',+ };++ if (knownByMime[mimeType]) return knownByMime[mimeType];++ try {+ const pathname = new URL(image.url).pathname;+ const ext = path.extname(pathname);+ return ext || undefined;+ } catch {+ return undefined;+ }+ }++ /**+ * Materialize an image attachment into a stable local file path so CLIs like+ * Codex can consume it through `--image <file>`.+ */+ private async resolveCliImagePath(image: HeterogeneousAgentImageAttachment): Promise<string> {+ const { buffer, mimeType } = await this.resolveImage(image);+ const cacheKey = this.getImageCacheKey(image.id);+ const ext = this.guessImageExtension(mimeType, image) || '';+ const filePath = path.join(this.fileCacheDir, `${cacheKey}${ext}`);++ try {+ await access(filePath);+ } catch {+ await mkdir(this.fileCacheDir, { recursive: true });+ await writeFile(filePath, buffer);+ }++ return filePath;+ }++ private async resolveCliImagePaths(+ imageList: HeterogeneousAgentImageAttachment[] = [],+ ): Promise<string[]> {+ const resolved = await Promise.all(+ imageList.map(async (image) => {+ try {+ return await this.resolveCliImagePath(image);+ } catch (err) {+ logger.error(`Failed to materialize image ${image.id} for CLI:`, err);+ return undefined;+ }+ }),+ );++ return resolved.filter(Boolean) as string[];+ }+/*** Build a stream-json user message with text + optional image content blocks.*/private async buildStreamJsonInput(prompt: string,- imageList: ImageAttachment[] = [],+ imageList: HeterogeneousAgentImageAttachment[] = [],): Promise<string> {const content: any[] = [{ text: prompt, type: 'text' }];@@ -226,10 +484,10 @@ export default class HeterogeneousAgentCtr extends ControllerModule {}}- return JSON.stringify({+ return `${JSON.stringify({message: { content, role: 'user' },type: 'user',- });+ })}\n`;}// ─── IPC methods ───@@ -241,6 +499,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {async startSession(params: StartSessionParams): Promise<StartSessionResult> {const sessionId = randomUUID();const agentType = params.agentType || 'claude-code';+ getHeterogeneousAgentDriver(agentType);this.sessions.set(sessionId, {// If resuming, pre-set the agent session ID so sendPrompt adds --resume@@ -251,6 +510,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {cwd: params.cwd,env: params.env,sessionId,+ resumeSessionId: params.resumeSessionId,});logger.info('Session created:', { agentType, sessionId });@@ -268,32 +528,31 @@ export default class HeterogeneousAgentCtr extends ControllerModule {const session = this.sessions.get(params.sessionId);if (!session) throw new Error(`Session not found: ${params.sessionId}`);- const preset = CLI_PRESETS[session.agentType];- if (!preset) throw new Error(`Unknown agent type: ${session.agentType}`);-- const useStdin = preset.promptMode === 'stdin';-- // Build stream-json payload up-front so any image download errors- // surface before the process is spawned.- let stdinPayload: string | undefined;- if (useStdin) {- stdinPayload = await this.buildStreamJsonInput(params.prompt, params.imageList ?? []);+ const preflightError = await this.getSpawnPreflightError(session);+ if (preflightError) {+ this.broadcast('heteroAgentSessionError', {+ error: preflightError,+ sessionId: session.sessionId,+ });+ throw new Error(preflightError.message);}+ const driver = getHeterogeneousAgentDriver(session.agentType);+ const spawnPlan = await driver.buildSpawnPlan({+ args: session.args,+ helpers: {+ buildClaudeStreamJsonInput: (prompt, imageList) =>+ this.buildStreamJsonInput(prompt, imageList),+ resolveCliImagePaths: (imageList) => this.resolveCliImagePaths(imageList),+ },+ imageList: params.imageList ?? [],+ prompt: params.prompt,+ resumeSessionId: session.agentSessionId,+ });+ const useStdin = spawnPlan.stdinPayload !== undefined;+return new Promise<void>((resolve, reject) => {- // Build CLI args: base preset + resume + user args- const cliArgs = [- ...preset.baseArgs,- ...(session.agentSessionId && preset.resumeArgs- ? preset.resumeArgs(session.agentSessionId)- : []),- ...session.args,- ];-- if (!useStdin && preset.promptMode === 'positional') {- // Positional mode: append prompt as a CLI arg (legacy / non-CC presets).- cliArgs.push(params.prompt);- }+ const cliArgs = spawnPlan.args;// Fall back to the user's Desktop so the process never inherits// the Electron parent's cwd (which is `/` when launched from Finder).@@ -318,45 +577,37 @@ export default class HeterogeneousAgentCtr extends ControllerModule {stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],});- // In stdin mode, write the stream-json message and close stdin.- if (useStdin && stdinPayload && proc.stdin) {+ // In stdin mode, write the prepared payload and close stdin.+ if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {const stdin = proc.stdin as Writable;- stdin.write(stdinPayload + '\n', () => {+ stdin.write(spawnPlan.stdinPayload, () => {stdin.end();});}session.process = proc;- let buffer = '';+ const streamProcessor = driver.createStreamProcessor();- // Stream stdout lines as raw events to Renderer- const stdout = proc.stdout as Readable;- stdout.on('data', (chunk: Buffer) => {- buffer += chunk.toString('utf8');- const lines = buffer.split('\n');- buffer = lines.pop() || '';-- for (const line of lines) {- const trimmed = line.trim();- if (!trimmed) continue;-- try {- const parsed = JSON.parse(trimmed);-- // Extract agent session ID from init event (for multi-turn)- if (parsed.type === 'system' && parsed.subtype === 'init' && parsed.session_id) {- session.agentSessionId = parsed.session_id;- }-- // Broadcast raw parsed JSON — Renderer handles all adaptation- this.broadcast('heteroAgentRawLine', {- line: parsed,- sessionId: session.sessionId,- });- } catch {- // Not valid JSON, skip+ const broadcastParsedOutputs = (parsedOutputs: HeterogeneousAgentParsedOutput[]) => {+ for (const parsedOutput of parsedOutputs) {+ if (parsedOutput.agentSessionId) {+ session.agentSessionId = parsedOutput.agentSessionId;}++ this.broadcast('heteroAgentRawLine', {+ line: parsedOutput.payload,+ sessionId: session.sessionId,+ });}+ };++ // Stream stdout events as raw provider payloads to Renderer.+ const stdout = proc.stdout as Readable;+ stdout.on('data', (chunk: Buffer) => {+ broadcastParsedOutputs(streamProcessor.push(chunk));+ });+ stdout.on('end', () => {+ broadcastParsedOutputs(streamProcessor.flush());});// Capture stderr@@ -368,11 +619,12 @@ export default class HeterogeneousAgentCtr extends ControllerModule {proc.on('error', (err) => {logger.error('Agent process error:', err);+ const sessionError = this.getSessionErrorPayload(err, session);this.broadcast('heteroAgentSessionError', {- error: err.message,+ error: sessionError,sessionId: session.sessionId,});- reject(err);+ reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));});proc.on('exit', (code, signal) => {@@ -396,11 +648,12 @@ export default class HeterogeneousAgentCtr extends ControllerModule {} else {const stderrOutput = stderrChunks.join('').trim();const errorMsg = stderrOutput || `Agent exited with code ${code}`;+ const sessionError = this.getSessionErrorPayload(errorMsg, session);this.broadcast('heteroAgentSessionError', {- error: errorMsg,+ error: sessionError,sessionId: session.sessionId,});- reject(new Error(errorMsg));+ reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));}});});diff --git a/apps/desktop/src/main/controllers/ToolDetectorCtr.ts b/apps/desktop/src/main/controllers/ToolDetectorCtr.tsindex 9f3d9b462ce..14a141873ff 100644--- a/apps/desktop/src/main/controllers/ToolDetectorCtr.ts+++ b/apps/desktop/src/main/controllers/ToolDetectorCtr.ts@@ -1,14 +1,18 @@-import { exec } from 'node:child_process';+import { execFile } from 'node:child_process';import { promisify } from 'node:util';-import type { ClaudeAuthStatus } from '@lobechat/electron-client-ipc';+import type {+ ClaudeAuthStatus,+ DetectHeterogeneousAgentCommandParams,+} from '@lobechat/electron-client-ipc';import type { ToolCategory, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';+import { detectHeterogeneousCliCommand } from '@/modules/toolDetectors';import { createLogger } from '@/utils/logger';import { ControllerModule, IpcMethod } from './index';-const execPromise = promisify(exec);+const execFilePromise = promisify(execFile);const logger = createLogger('controllers:ToolDetectorCtr');@@ -34,6 +38,14 @@ export default class ToolDetectorCtr extends ControllerModule {return this.manager.detect(name, force);}+ @IpcMethod()+ async detectHeterogeneousAgentCommand(+ params: DetectHeterogeneousAgentCommandParams,+ ): Promise<ToolStatus> {+ logger.debug('Detecting heterogeneous agent command:', params);+ return detectHeterogeneousCliCommand(params.agentType, params.command);+ }+/*** Detect all registered tools*/@@ -125,9 +137,14 @@ export default class ToolDetectorCtr extends ControllerModule {* Returns null if the CLI is unavailable or the command fails.*/@IpcMethod()- async getClaudeAuthStatus(): Promise<ClaudeAuthStatus | null> {+ async getClaudeAuthStatus(command = 'claude'): Promise<ClaudeAuthStatus | null> {+ const resolvedCommand = command.trim() || 'claude';+try {- const { stdout } = await execPromise('claude auth status --json', { timeout: 5000 });+ const { stdout } = await execFilePromise(resolvedCommand, ['auth', 'status', '--json'], {+ timeout: 5000,+ windowsHide: true,+ });return JSON.parse(stdout.trim()) as ClaudeAuthStatus;} catch (error) {logger.debug('Failed to get claude auth status:', error);diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex b69c695e7cd..b6070b8f1a0 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { PassThrough } from 'node:stream';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';@@ -32,18 +33,34 @@ vi.mock('@/utils/logger', () => ({// Captures the most recent spawn() call so sendPrompt tests can assert on argv.const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];let nextFakeProc: any = null;-vi.mock('node:child_process', () => ({- spawn: (command: string, args: string[], options: any) => {- spawnCalls.push({ args, command, options });- return nextFakeProc;- },+const { execFileMock } = vi.hoisted(() => ({+ execFileMock: vi.fn(),}));+vi.mock('node:child_process', async (importOriginal) => {+ const actual = (await importOriginal()) as Record<string, unknown>;++ return {+ ...actual,+ execFile: execFileMock,+ spawn: (command: string, args: string[], options: any) => {+ spawnCalls.push({ args, command, options });+ nextFakeProc?.__start?.();+ return nextFakeProc;+ },+ };+});/*** Build a fake ChildProcess that immediately exits cleanly. Records every* stdin write on the returned `writes` array so tests can inspect the payload.*/-const createFakeProc = () => {+const createFakeProc = ({+ exitCode = 0,+ stdoutLines = [],+}: {+ exitCode?: number;+ stdoutLines?: string[];+} = {}) => {const proc = new EventEmitter() as any;const stdout = new PassThrough();const stderr = new PassThrough();@@ -60,15 +77,26 @@ const createFakeProc = () => {};proc.kill = vi.fn();proc.killed = false;- // Exit asynchronously so the Promise returned by sendPrompt resolves cleanly.- setImmediate(() => {- stdout.end();- stderr.end();- proc.emit('exit', 0);- });+ let started = false;+ proc.__start = () => {+ if (started) return;+ started = true;+ // Exit asynchronously so the Promise returned by sendPrompt resolves cleanly.+ setImmediate(() => {+ for (const line of stdoutLines) {+ stdout.write(line);+ }+ stdout.end();+ stderr.end();+ proc.emit('exit', exitCode);+ });+ };return { proc, writes };};+const getFlagValues = (args: string[], flag: string) =>+ args.flatMap((arg, index) => (arg === flag ? [args[index + 1]] : []));+describe('HeterogeneousAgentCtr', () => {let appStoragePath: string;@@ -144,10 +172,15 @@ describe('HeterogeneousAgentCtr', () => {describe('sendPrompt (claude-code)', () => {beforeEach(() => {spawnCalls.length = 0;+ execFileMock.mockReset();});- const runSendPrompt = async (prompt: string, sessionOverrides: Record<string, any> = {}) => {- const { proc, writes } = createFakeProc();+ const runSendPrompt = async (+ prompt: string,+ sessionOverrides: Record<string, any> = {},+ stdoutLines: string[] = [],+ ) => {+ const { proc, writes } = createFakeProc({ stdoutLines });nextFakeProc = proc;const ctr = new HeterogeneousAgentCtr({@@ -162,7 +195,7 @@ describe('HeterogeneousAgentCtr', () => {await ctr.sendPrompt({ prompt, sessionId });const { args: cliArgs, command, options } = spawnCalls[0];- return { cliArgs, command, options, writes };+ return { cliArgs, command, ctr, options, sessionId, writes };};it('passes prompt via stdin stream-json — never as a positional arg', async () => {@@ -221,5 +254,258 @@ describe('HeterogeneousAgentCtr', () => {expect(options.cwd).toBe(explicitCwd);});++ it('captures the Claude Code session id from stream-json init events', async () => {+ const { ctr, sessionId } = await runSendPrompt('hello', {}, [+ `${JSON.stringify({ session_id: 'sess_cc_123', subtype: 'init', type: 'system' })}\n`,+ ]);++ await expect(ctr.getSessionInfo({ sessionId })).resolves.toEqual({+ agentSessionId: 'sess_cc_123',+ });+ });+ });++ describe('sendPrompt (codex)', () => {+ beforeEach(() => {+ spawnCalls.length = 0;+ execFileMock.mockReset();+ });++ const runSendPrompt = async (+ prompt: string,+ sessionOverrides: Record<string, any> = {},+ stdoutLines: string[] = [],+ sendPromptOverrides: Partial<{ imageList: Array<{ id: string; url: string }> }> = {},+ ) => {+ const { proc, writes } = createFakeProc({ stdoutLines });+ nextFakeProc = proc;++ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'codex',+ command: 'codex',+ ...sessionOverrides,+ });+ await ctr.sendPrompt({ prompt, sessionId, ...sendPromptOverrides });++ const { args: cliArgs, command, options } = spawnCalls[0];+ return { cliArgs, command, ctr, options, sessionId, writes };+ };++ it('fails fast when Codex CLI is unavailable instead of attempting spawn', async () => {+ const detect = vi.fn().mockResolvedValue({ available: false });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ toolDetectorManager: { detect },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'codex',+ command: 'codex',+ });++ await expect(ctr.sendPrompt({ prompt: 'hello', sessionId })).rejects.toThrow(+ 'Codex CLI was not found',+ );++ expect(detect).toHaveBeenCalledWith('codex', true);+ expect(spawnCalls).toHaveLength(0);+ });++ it('fails fast when Claude Code CLI is unavailable instead of attempting spawn', async () => {+ const detect = vi.fn().mockResolvedValue({ available: false });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ toolDetectorManager: { detect },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'claude-code',+ command: 'claude',+ });++ await expect(ctr.sendPrompt({ prompt: 'hello', sessionId })).rejects.toThrow(+ 'Claude Code CLI was not found',+ );++ expect(detect).toHaveBeenCalledWith('claude', true);+ expect(spawnCalls).toHaveLength(0);+ });++ it('fails fast when a customized Claude command is unavailable instead of checking the default detector', async () => {+ execFileMock.mockImplementation(+ (+ file: string,+ _args: string[],+ optionsOrCallback: unknown,+ callback?: (error: Error | null, stdout: string, stderr: string) => void,+ ) => {+ const resolvedCallback =+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;++ resolvedCallback?.(+ Object.assign(new Error(`${file} not found`), { code: 'ENOENT' }),+ '',+ '',+ );+ },+ );++ const detect = vi.fn().mockResolvedValue({ available: true });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ toolDetectorManager: { detect },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'claude-code',+ command: 'claude-alt',+ });++ await expect(ctr.sendPrompt({ prompt: 'hello', sessionId })).rejects.toThrow(+ 'Claude Code CLI was not found',+ );++ expect(detect).not.toHaveBeenCalled();+ expect(spawnCalls).toHaveLength(0);+ });++ it('passes prompt via stdin to codex exec instead of argv', async () => {+ const prompt = '--run a shell-like prompt safely';+ const { cliArgs, command, writes } = await runSendPrompt(prompt);++ expect(command).toBe('codex');+ expect(cliArgs).not.toContain(prompt);+ expect(cliArgs).toEqual(+ expect.arrayContaining(['exec', '--json', '--skip-git-repo-check', '--full-auto', '-']),+ );+ expect(writes).toEqual([prompt]);+ });++ it('materializes image attachments into local files and forwards them via --image', async () => {+ const imageList = [+ { id: 'image-1', url: 'data:image/png;base64,UE5HX1RFU1Q=' },+ { id: 'image-2', url: 'data:image/jpeg;base64,SlBFR19URVNU' },+ ];+ const { cliArgs, writes } = await runSendPrompt('describe these screenshots', {}, [], {+ imageList,+ });++ const imagePaths = getFlagValues(cliArgs, '--image');++ expect(cliArgs).not.toContain('describe these screenshots');+ expect(cliArgs.filter((arg) => arg === '--image')).toHaveLength(2);+ expect(imagePaths).toHaveLength(2);+ expect(imagePaths[0]).toMatch(/\.png$/);+ expect(imagePaths[1]).toMatch(/\.jpg$/);+ expect(+ imagePaths.every((filePath) =>+ filePath.startsWith(path.join(appStoragePath, 'heteroAgent/files')),+ ),+ ).toBe(true);+ await expect(+ Promise.all(imagePaths.map((filePath) => readFile(filePath, 'utf8'))),+ ).resolves.toEqual(['PNG_TEST', 'JPEG_TEST']);+ expect(writes).toEqual(['describe these screenshots']);+ });++ it('skips images that fail to materialize and still forwards the remaining --image args', async () => {+ const imageList = [+ { id: 'good-image', url: 'data:image/png;base64,VkFMSURfSU1BR0U=' },+ { id: 'bad-image', url: 'bad://broken-image' },+ ];+ const { cliArgs, writes } = await runSendPrompt('inspect the valid screenshot only', {}, [], {+ imageList,+ });++ const imagePaths = getFlagValues(cliArgs, '--image');++ expect(cliArgs.filter((arg) => arg === '--image')).toHaveLength(1);+ expect(imagePaths).toHaveLength(1);+ expect(imagePaths[0]).toMatch(/\.png$/);+ await expect(readFile(imagePaths[0], 'utf8')).resolves.toBe('VALID_IMAGE');+ expect(writes).toEqual(['inspect the valid screenshot only']);+ });++ it('uses codex exec resume syntax when continuing an existing thread', async () => {+ const { cliArgs } = await runSendPrompt('continue', { resumeSessionId: 'thread_abc' });++ expect(cliArgs.slice(0, 2)).toEqual(['exec', 'resume']);+ expect(cliArgs).toContain('thread_abc');+ expect(cliArgs).not.toContain('--resume');+ expect(cliArgs.at(-1)).toBe('-');+ });++ it('captures the Codex thread id from json output for later resume', async () => {+ const { ctr, sessionId } = await runSendPrompt('hello', {}, [+ `${JSON.stringify({ thread_id: 'thread_codex_123', type: 'thread.started' })}\n`,+ ]);++ await expect(ctr.getSessionInfo({ sessionId })).resolves.toEqual({+ agentSessionId: 'thread_codex_123',+ });+ });++ it('classifies stale Codex resume stderr as a structured resume error', () => {+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const payload = (ctr as any).getSessionErrorPayload(+ 'No conversation found for thread thread_stale_123',+ {+ agentSessionId: 'thread_stale_123',+ agentType: 'codex',+ args: [],+ command: 'codex',+ cwd: '/Users/fake/projects/repo',+ resumeSessionId: 'thread_stale_123',+ sessionId: 'session-1',+ },+ );++ expect(payload).toEqual({+ agentType: 'codex',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: 'codex',+ message: 'The saved Codex thread could not be found, so it can no longer be resumed.',+ resumeSessionId: 'thread_stale_123',+ stderr: 'No conversation found for thread thread_stale_123',+ workingDirectory: '/Users/fake/projects/repo',+ });+ });++ it('classifies CLI authentication failures as auth-required errors', () => {+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const payload = (ctr as any).getSessionErrorPayload(+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}',+ {+ agentType: 'claude-code',+ args: [],+ command: 'claude',+ sessionId: 'session-1',+ },+ );++ expect(payload).toEqual({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ command: 'claude',+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr:+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}',+ });+ });});});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsnew file mode 100644index 00000000000..40aea86096f--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -0,0 +1,41 @@+import { JsonlStreamProcessor } from '../jsonlProcessor';+import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';++const CLAUDE_CODE_BASE_ARGS = [+ '-p',+ '--input-format',+ 'stream-json',+ '--output-format',+ 'stream-json',+ '--verbose',+ '--include-partial-messages',+ '--permission-mode',+ 'bypassPermissions',+] as const;++export const claudeCodeDriver: HeterogeneousAgentDriver = {+ async buildSpawnPlan({+ args,+ helpers,+ imageList,+ prompt,+ resumeSessionId,+ }: HeterogeneousAgentBuildPlanParams) {+ const stdinPayload = await helpers.buildClaudeStreamJsonInput(prompt, imageList);++ return {+ args: [+ ...CLAUDE_CODE_BASE_ARGS,+ ...(resumeSessionId ? ['--resume', resumeSessionId] : []),+ ...args,+ ],+ stdinPayload,+ };+ },+ createStreamProcessor() {+ return new JsonlStreamProcessor({+ extractSessionId: (payload) =>+ payload?.type === 'system' && payload?.subtype === 'init' ? payload?.session_id : undefined,+ });+ },+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.tsnew file mode 100644index 00000000000..5faf4455ed4--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts@@ -0,0 +1,50 @@+import { JsonlStreamProcessor } from '../jsonlProcessor';+import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';++const CODEX_REQUIRED_ARGS = ['--json', '--skip-git-repo-check'] as const;+const CODEX_AUTO_EXECUTION_FLAGS = [+ '--full-auto',+ '--dangerously-bypass-approvals-and-sandbox',+ '--sandbox',+ '-s',+] as const;++const hasAnyFlag = (args: string[], flags: readonly string[]) =>+ args.some((arg) => flags.includes(arg as (typeof flags)[number]));++const buildCodexOptionArgs = async ({+ args,+ helpers,+ imageList,+}: Pick<HeterogeneousAgentBuildPlanParams, 'args' | 'helpers' | 'imageList'>) => {+ const imagePaths = await helpers.resolveCliImagePaths(imageList);+ const imageArgs = imagePaths.flatMap((filePath) => ['--image', filePath]);+ const autoExecutionArgs = hasAnyFlag(args, CODEX_AUTO_EXECUTION_FLAGS) ? [] : ['--full-auto'];++ return [...CODEX_REQUIRED_ARGS, ...autoExecutionArgs, ...imageArgs, ...args];+};++export const codexDriver: HeterogeneousAgentDriver = {+ async buildSpawnPlan({+ args,+ helpers,+ imageList,+ prompt,+ resumeSessionId,+ }: HeterogeneousAgentBuildPlanParams) {+ const optionArgs = await buildCodexOptionArgs({ args, helpers, imageList });++ return {+ args: resumeSessionId+ ? ['exec', 'resume', ...optionArgs, resumeSessionId, '-']+ : ['exec', ...optionArgs, '-'],+ stdinPayload: prompt,+ };+ },+ createStreamProcessor() {+ return new JsonlStreamProcessor({+ extractSessionId: (payload) =>+ payload?.type === 'thread.started' ? payload?.thread_id : undefined,+ });+ },+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsnew file mode 100644index 00000000000..2e654f9ebf6--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -0,0 +1,18 @@+import { claudeCodeDriver } from './drivers/claudeCode';+import { codexDriver } from './drivers/codex';+import type { HeterogeneousAgentDriver } from './types';++const heterogeneousAgentDrivers: Record<string, HeterogeneousAgentDriver> = {+ 'claude-code': claudeCodeDriver,+ 'codex': codexDriver,+};++export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAgentDriver => {+ const driver = heterogeneousAgentDrivers[agentType];++ if (!driver) {+ throw new Error(`Unknown heterogeneous agent type: ${agentType}`);+ }++ return driver;+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/jsonlProcessor.ts b/apps/desktop/src/main/modules/heterogeneousAgent/jsonlProcessor.tsnew file mode 100644index 00000000000..f4cb6a724cc--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/jsonlProcessor.ts@@ -0,0 +1,61 @@+import type { HeterogeneousAgentParsedOutput, HeterogeneousAgentStreamProcessor } from './types';++export interface JsonlProcessorOptions {+ extractSessionId?: (payload: any) => string | undefined;+}++/**+ * Parses stdout as JSONL / NDJSON while tolerating non-JSON noise lines.+ * Different CLIs still end up sharing this framing logic even when the+ * payload schema differs.+ */+export class JsonlStreamProcessor implements HeterogeneousAgentStreamProcessor {+ private buffer = '';++ constructor(private readonly options: JsonlProcessorOptions = {}) {}++ push(chunk: Buffer | string): HeterogeneousAgentParsedOutput[] {+ this.buffer += chunk instanceof Buffer ? chunk.toString('utf8') : chunk;+ return this.drainCompleteLines();+ }++ flush(): HeterogeneousAgentParsedOutput[] {+ const trailing = this.buffer.trim();+ this.buffer = '';++ if (!trailing) return [];++ try {+ return [this.toParsedOutput(JSON.parse(trailing))];+ } catch {+ return [];+ }+ }++ private drainCompleteLines(): HeterogeneousAgentParsedOutput[] {+ const lines = this.buffer.split('\n');+ this.buffer = lines.pop() || '';++ const parsed: HeterogeneousAgentParsedOutput[] = [];++ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) continue;++ try {+ parsed.push(this.toParsedOutput(JSON.parse(trimmed)));+ } catch {+ // Ignore non-JSON stdout noise.+ }+ }++ return parsed;+ }++ private toParsedOutput(payload: any): HeterogeneousAgentParsedOutput {+ return {+ agentSessionId: this.options.extractSessionId?.(payload),+ payload,+ };+ }+}diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsnew file mode 100644index 00000000000..4d8a66085f4--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -0,0 +1,42 @@+export interface HeterogeneousAgentImageAttachment {+ id: string;+ url: string;+}++export interface HeterogeneousAgentBuildPlan {+ args: string[];+ stdinPayload?: string;+}++export interface HeterogeneousAgentBuildPlanHelpers {+ buildClaudeStreamJsonInput: (+ prompt: string,+ imageList: HeterogeneousAgentImageAttachment[],+ ) => Promise<string>;+ resolveCliImagePaths: (imageList: HeterogeneousAgentImageAttachment[]) => Promise<string[]>;+}++export interface HeterogeneousAgentBuildPlanParams {+ args: string[];+ helpers: HeterogeneousAgentBuildPlanHelpers;+ imageList: HeterogeneousAgentImageAttachment[];+ prompt: string;+ resumeSessionId?: string;+}++export interface HeterogeneousAgentParsedOutput {+ agentSessionId?: string;+ payload: any;+}++export interface HeterogeneousAgentStreamProcessor {+ flush: () => HeterogeneousAgentParsedOutput[];+ push: (chunk: Buffer | string) => HeterogeneousAgentParsedOutput[];+}++export interface HeterogeneousAgentDriver {+ buildSpawnPlan: (+ params: HeterogeneousAgentBuildPlanParams,+ ) => Promise<HeterogeneousAgentBuildPlan>;+ createStreamProcessor: () => HeterogeneousAgentStreamProcessor;+}diff --git a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts b/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.tsindex be848dfb845..79d7e920015 100644--- a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts+++ b/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts@@ -1,58 +1,107 @@-import { exec } from 'node:child_process';+import { execFile } from 'node:child_process';import { platform } from 'node:os';import { promisify } from 'node:util';import type { IToolDetector, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';-const execPromise = promisify(exec);+const execFilePromise = promisify(execFile);-/**- * Detector that resolves a command path via which/where, then validates- * the binary by matching `--version` (or `--help`) output against a keyword- * to avoid collisions with unrelated executables of the same name.- */-const createValidatedDetector = (options: {- candidates: string[];+type HeterogeneousCliAgentType = 'claude-code' | 'codex';++interface ValidatedDetectorOptions {description: string;name: string;priority: number;validateFlag?: string;validateKeywords: string[];-}): IToolDetector => {- const {- name,- description,- priority,- candidates,- validateFlag = '--version',- validateKeywords,- } = options;+}++const resolveCommandPath = async (command: string): Promise<string | undefined> => {+ const trimmedCommand = command.trim();+ if (!trimmedCommand) return;++ const whichCommand = platform() === 'win32' ? 'where' : 'which';++ try {+ const { stdout } = await execFilePromise(whichCommand, [trimmedCommand], { timeout: 3000 });+ return stdout.trim().split(/\r?\n/)[0] || trimmedCommand;+ } catch {+ return trimmedCommand;+ }+};++const detectValidatedCommand = async (+ command: string,+ options: Pick<ValidatedDetectorOptions, 'validateFlag' | 'validateKeywords'>,+): Promise<ToolStatus> => {+ const trimmedCommand = command.trim();+ if (!trimmedCommand) return { available: false };++ const { validateFlag = '--version', validateKeywords } = options;++ try {+ const { stderr, stdout } = await execFilePromise(trimmedCommand, [validateFlag], {+ timeout: 5000,+ windowsHide: true,+ });+ const output = `${stdout}\n${stderr}`.trim();+ const loweredOutput = output.toLowerCase();++ if (!validateKeywords.some((keyword) => loweredOutput.includes(keyword.toLowerCase()))) {+ return { available: false };+ }++ return {+ available: true,+ path: await resolveCommandPath(trimmedCommand),+ version: output.split(/\r?\n/)[0],+ };+ } catch {+ return { available: false };+ }+};++const HETEROGENEOUS_CLI_AGENT_OPTIONS = {+ 'claude-code': {+ validateKeywords: ['claude code'],+ },+ 'codex': {+ validateKeywords: ['codex'],+ },+} as const satisfies Record<+ HeterogeneousCliAgentType,+ Pick<ValidatedDetectorOptions, 'validateKeywords'>+>;++export const detectHeterogeneousCliCommand = async (+ agentType: HeterogeneousCliAgentType,+ command: string,+): Promise<ToolStatus> => {+ const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];+ if (!validator) return { available: false };++ return detectValidatedCommand(command, validator);+};++/**+ * Detector that resolves a command path via which/where, then validates+ * the binary by matching `--version` (or `--help`) output against a keyword+ * to avoid collisions with unrelated executables of the same name.+ */+const createValidatedDetector = (+ options: ValidatedDetectorOptions & {+ candidates: string[];+ },+): IToolDetector => {+ const { candidates, description, name, priority, ...validation } = options;return {description,async detect(): Promise<ToolStatus> {- const whichCmd = platform() === 'win32' ? 'where' : 'which';-for (const cmd of candidates) {- try {- const { stdout: pathOut } = await execPromise(`${whichCmd} ${cmd}`, { timeout: 3000 });- const toolPath = pathOut.trim().split('\n')[0];- if (!toolPath) continue;-- const { stdout: out } = await execPromise(`${cmd} ${validateFlag}`, { timeout: 5000 });- const output = out.trim();- const lowered = output.toLowerCase();- if (!validateKeywords.some((kw) => lowered.includes(kw.toLowerCase()))) continue;-- return {- available: true,- path: toolPath,- version: output.split('\n')[0],- };- } catch {- continue;- }+ const status = await detectValidatedCommand(cmd, validation);+ if (status.available) return status;}return { available: false };diff --git a/apps/desktop/src/main/modules/toolDetectors/index.ts b/apps/desktop/src/main/modules/toolDetectors/index.tsindex 5313ecd787b..6ac7c3e357a 100644--- a/apps/desktop/src/main/modules/toolDetectors/index.ts+++ b/apps/desktop/src/main/modules/toolDetectors/index.ts@@ -6,7 +6,7 @@*/export { browserAutomationDetectors } from './agentBrowserDetectors';-export { cliAgentDetectors } from './cliAgentDetectors';+export { cliAgentDetectors, detectHeterogeneousCliCommand } from './cliAgentDetectors';export { astSearchDetectors, contentSearchDetectors } from './contentSearchDetectors';export { fileSearchDetectors } from './fileSearchDetectors';export { runtimeEnvironmentDetectors } from './runtimeEnvironmentDetectors';diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 42774412cc1..77c8a3ef254 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -36,7 +36,47 @@"builtinCopilot": "Built-in Copilot","chatList.expandMessage": "Expand Message","chatList.longMessageDetail": "View Details",+ "claudeCodeInstallGuide.actions.openDocs": "Open Install Guide",+ "claudeCodeInstallGuide.actions.openSystemTools": "Open System Tools",+ "claudeCodeInstallGuide.afterInstall": "After installing, run Claude Code once to sign in, then retry your message or click Re-detect in System Tools.",+ "claudeCodeInstallGuide.desc": "Claude Code needs the Claude Code CLI to run locally. Install it and make sure the `claude` command is available in your PATH.",+ "claudeCodeInstallGuide.installWithBrew": "Homebrew",+ "claudeCodeInstallGuide.installWithNpm": "Recommended install",+ "claudeCodeInstallGuide.menuNotification.title": "Claude Code CLI not found",+ "claudeCodeInstallGuide.reason": "LobeHub could not start Claude Code: {{message}}",+ "claudeCodeInstallGuide.title": "Install Claude Code CLI","clearCurrentMessages": "Clear current session messages",+ "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.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",+ "cliAuthGuide.title": "Sign in to {{name}}",+ "cliRateLimitGuide.actions.openSystemTools": "Open System Tools",+ "cliRateLimitGuide.afterReset": "Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.",+ "cliRateLimitGuide.desc": "{{name}} has reached its current usage limit and cannot continue this run right now.",+ "cliRateLimitGuide.limitType": "Limit window",+ "cliRateLimitGuide.limitTypes.weekCycle": "Week cycle",+ "cliRateLimitGuide.relative.day_one": "{{count}} day",+ "cliRateLimitGuide.relative.day_other": "{{count}} days",+ "cliRateLimitGuide.relative.hour_one": "{{count}} hour",+ "cliRateLimitGuide.relative.hour_other": "{{count}} hours",+ "cliRateLimitGuide.relative.minute_one": "{{count}} minute",+ "cliRateLimitGuide.relative.minute_other": "{{count}} minutes",+ "cliRateLimitGuide.relative.soon": "Resets soon",+ "cliRateLimitGuide.resetAt": "Resets at",+ "cliRateLimitGuide.resetInApprox": "Resets in about {{duration}}",+ "cliRateLimitGuide.title": "{{name}} usage limit reached",+ "codexInstallGuide.actions.openDocs": "Open Install Guide",+ "codexInstallGuide.actions.openSystemTools": "Open System Tools",+ "codexInstallGuide.afterInstall": "After installing, run Codex once to sign in, then retry your message or click Re-detect in System Tools.",+ "codexInstallGuide.desc": "Codex Agent needs the Codex CLI to run locally. Install it and make sure the `codex` command is available in your PATH.",+ "codexInstallGuide.installWithBrew": "Homebrew (macOS)",+ "codexInstallGuide.installWithNpm": "Recommended install",+ "codexInstallGuide.menuNotification.title": "Codex CLI not found",+ "codexInstallGuide.reason": "LobeHub could not start Codex: {{message}}",+ "codexInstallGuide.title": "Install Codex CLI","compressedHistory": "Compressed History","compression.cancel": "Uncompress","compression.cancelConfirm": "Are you sure you want to uncompress? This will restore the original messages.",@@ -139,6 +179,7 @@"heteroAgent.fullAccess.label": "Full access","heteroAgent.fullAccess.tooltip": "Claude Code runs locally with full read/write access to the working directory. Switching permission modes is not available yet.","heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.",+ "heteroAgent.resumeReset.resumeFailed": "The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.","heteroAgent.switchCwd.cancel": "Cancel","heteroAgent.switchCwd.content": "Claude Code sessions are pinned to a working directory. Switching will start a new session for this topic — chat messages stay, but the previous session context cannot be resumed.","heteroAgent.switchCwd.ok": "Switch and start new session",@@ -247,6 +288,7 @@"minimap.senderUser": "You","newAgent": "Create Agent","newClaudeCodeAgent": "Add Claude Code",+ "newCodexAgent": "Add Codex","newGroupChat": "Create Group","newPage": "Create Page","noAgentsYet": "This group has no members yet. Click the + button to invite agents.",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex f01f6255b85..7e52e665425 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -191,11 +191,6 @@"analytics.telemetry.desc": "Help us improve {{appName}} with anonymous usage data","analytics.telemetry.title": "Send Anonymous Usage Data","analytics.title": "Analytics",- "ccStatus.account.label": "Account",- "ccStatus.detecting": "Detecting Claude Code CLI...",- "ccStatus.redetect": "Re-detect",- "ccStatus.title": "Claude Code CLI",- "ccStatus.unavailable": "Claude Code CLI not found. Please install or configure it.","checking": "Checking...","checkingPermissions": "Checking permissions...","creds.actions.delete": "Delete",@@ -292,6 +287,10 @@"header.sessionDesc": "Agent Profile and session preferences","header.sessionWithName": "Session Settings · {{name}}","header.title": "Settings",+ "heterogeneousStatus.account.label": "Account",+ "heterogeneousStatus.detecting": "Detecting {{name}} CLI...",+ "heterogeneousStatus.redetect": "Re-detect",+ "heterogeneousStatus.unavailable": "{{name}} CLI not found. Please install or configure it.","hotkey.clearBinding": "Clear binding","hotkey.conflicts": "Conflicts with existing hotkeys","hotkey.errors.CONFLICT": "Hotkey conflict: This hotkey is already assigned to another function",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 354b1ed3aeb..571c774917e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -36,7 +36,47 @@"builtinCopilot": "内置 Copilot","chatList.expandMessage": "展开消息","chatList.longMessageDetail": "查看详情",+ "claudeCodeInstallGuide.actions.openDocs": "打开安装指南",+ "claudeCodeInstallGuide.actions.openSystemTools": "打开系统工具",+ "claudeCodeInstallGuide.afterInstall": "安装完成后,请先运行一次 Claude Code 完成登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",+ "claudeCodeInstallGuide.desc": "Claude Code 需要本地安装 Claude Code CLI 才能运行。请先安装,并确保 `claude` 命令已加入 PATH。",+ "claudeCodeInstallGuide.installWithBrew": "Homebrew 安装",+ "claudeCodeInstallGuide.installWithNpm": "推荐安装方式",+ "claudeCodeInstallGuide.menuNotification.title": "未找到 Claude Code CLI",+ "claudeCodeInstallGuide.reason": "LobeHub 无法启动 Claude Code:{{message}}",+ "claudeCodeInstallGuide.title": "安装 Claude Code CLI","clearCurrentMessages": "清空当前会话消息",+ "cliAuthGuide.actions.openDocs": "打开登录指南",+ "cliAuthGuide.actions.openSystemTools": "打开系统工具",+ "cliAuthGuide.afterLogin": "重新登录或更新凭证后,请重试刚才的消息。你也可以去系统工具里重新检测。",+ "cliAuthGuide.desc": "{{name}} 当前无法继续运行,可能是登录态已失效,或凭证已经不可用。",+ "cliAuthGuide.errorDetails": "错误详情",+ "cliAuthGuide.runCommand": "在终端执行",+ "cliAuthGuide.title": "登录 {{name}}",+ "cliRateLimitGuide.actions.openSystemTools": "打开系统工具",+ "cliRateLimitGuide.afterReset": "请等到重置时间后再重试这条消息。如果你当前使用的是 API 授权,也可以检查对应提供商的额度和计费状态。",+ "cliRateLimitGuide.desc": "{{name}} 已达到当前使用上限,这次运行暂时无法继续。",+ "cliRateLimitGuide.limitType": "限制周期",+ "cliRateLimitGuide.limitTypes.weekCycle": "Week 周期",+ "cliRateLimitGuide.relative.day_one": "{{count}} 天",+ "cliRateLimitGuide.relative.day_other": "{{count}} 天",+ "cliRateLimitGuide.relative.hour_one": "{{count}} 小时",+ "cliRateLimitGuide.relative.hour_other": "{{count}} 小时",+ "cliRateLimitGuide.relative.minute_one": "{{count}} 分钟",+ "cliRateLimitGuide.relative.minute_other": "{{count}} 分钟",+ "cliRateLimitGuide.relative.soon": "即将重置",+ "cliRateLimitGuide.resetAt": "重置时间",+ "cliRateLimitGuide.resetInApprox": "约 {{duration}} 后重置",+ "cliRateLimitGuide.title": "{{name}} 已达到使用上限",+ "codexInstallGuide.actions.openDocs": "打开安装指南",+ "codexInstallGuide.actions.openSystemTools": "打开系统工具",+ "codexInstallGuide.afterInstall": "安装完成后,请先运行一次 Codex 完成登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",+ "codexInstallGuide.desc": "Codex Agent 需要本地安装 Codex CLI 才能运行。请先安装,并确保 `codex` 命令已加入 PATH。",+ "codexInstallGuide.installWithBrew": "Homebrew 安装(macOS)",+ "codexInstallGuide.installWithNpm": "推荐安装方式",+ "codexInstallGuide.menuNotification.title": "未找到 Codex CLI",+ "codexInstallGuide.reason": "LobeHub 无法启动 Codex:{{message}}",+ "codexInstallGuide.title": "安装 Codex CLI","compressedHistory": "压缩历史","compression.cancel": "取消压缩","compression.cancelConfirm": "确定要取消压缩吗?这将恢复原始消息。",@@ -139,6 +179,7 @@"heteroAgent.fullAccess.label": "完全访问权限","heteroAgent.fullAccess.tooltip": "Claude Code 在本地运行,对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。","heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。",+ "heteroAgent.resumeReset.resumeFailed": "已保存的 Codex 线程无法安全恢复,当前话题已自动开启新会话。","heteroAgent.switchCwd.cancel": "取消","heteroAgent.switchCwd.content": "Claude Code 会话会绑定到具体的工作目录。切换后将为当前话题开启一个新会话——消息记录会保留,但之前会话的上下文无法恢复。","heteroAgent.switchCwd.ok": "切换并开启新会话",@@ -247,6 +288,7 @@"minimap.senderUser": "你","newAgent": "创建助理","newClaudeCodeAgent": "添加 Claude Code",+ "newCodexAgent": "添加 Codex","newGroupChat": "创建群组","newPage": "创建文稿","noAgentsYet": "这个群组还没有成员。点击「+」邀请助理加入",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 6f7e021da6b..b4b5d757063 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -191,11 +191,6 @@"analytics.telemetry.desc": "通过匿名使用数据帮助我们改进 {{appName}}","analytics.telemetry.title": "发送匿名使用数据","analytics.title": "数据统计",- "ccStatus.account.label": "账号",- "ccStatus.detecting": "正在检测 Claude Code CLI…",- "ccStatus.redetect": "重新检测",- "ccStatus.title": "Claude Code CLI",- "ccStatus.unavailable": "未检测到 Claude Code CLI,请先安装或配置","checking": "检查中…","checkingPermissions": "检查权限中…","creds.actions.delete": "删除",@@ -292,6 +287,17 @@"header.sessionDesc": "助理档案与会话偏好","header.sessionWithName": "会话设置 · {{name}}","header.title": "设置",+ "heterogeneousStatus.account.label": "账号",+ "heterogeneousStatus.auth.api": "API",+ "heterogeneousStatus.auth.label": "授权方式",+ "heterogeneousStatus.auth.subscription": "订阅",+ "heterogeneousStatus.command.edit": "编辑启动命令",+ "heterogeneousStatus.command.label": "启动命令",+ "heterogeneousStatus.command.placeholder": "命令名或绝对路径",+ "heterogeneousStatus.detecting": "正在检测 {{name}} CLI…",+ "heterogeneousStatus.plan.label": "套餐",+ "heterogeneousStatus.redetect": "重新检测",+ "heterogeneousStatus.unavailable": "未检测到 {{name}} CLI,请先安装或配置","hotkey.clearBinding": "清除绑定","hotkey.conflicts": "与现有快捷键冲突","hotkey.errors.CONFLICT": "快捷键冲突:该快捷键已被其他功能占用",diff --git a/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx b/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsxindex f11506329d0..ae24a890d57 100644--- a/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx+++ b/packages/builtin-tool-activator/src/client/Inspector/ActivateSkill/index.tsx@@ -1,24 +1,59 @@'use client';import { type BuiltinInspectorProps } from '@lobechat/types';-import { cx } from 'antd-style';+import { SkillsIcon } from '@lobehub/ui/icons';+import { createStaticStyles, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ActivateSkillParams, ActivateSkillState } from '../../../types';+const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ gap: 6px;+ align-items: center;++ min-width: 0;+ max-width: 100%;+ margin-inline-start: 6px;+ padding-block: 3px;+ padding-inline: 10px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 999px;++ background: ${cssVar.colorBgContainer};+ `,+ skillIcon: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextDescription};+ `,+ skillName: css`+ overflow: hidden;++ min-width: 0;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));+export const ActivateSkillInspector = memo<BuiltinInspectorProps<ActivateSkillParams, ActivateSkillState>>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {const { t } = useTranslation('plugin');- const name = args?.name || partialArgs?.name || '';- const activatedName = pluginState?.name;+ const name = args?.name || partialArgs?.name;+ const displayName = pluginState?.name || name;if (isArgumentsStreaming) {- if (!name)+ if (!displayName)return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-skills.apiName.activateSkill')}</span>@@ -28,17 +63,23 @@ export const ActivateSkillInspector = memo<return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>- <span>{name}</span>+ <span className={styles.chip}>+ <SkillsIcon className={styles.skillIcon} size={12} />+ <span className={styles.skillName}>{displayName}</span>+ </span></div>);}return (<div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span>- <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>- <span className={highlightTextStyles.primary}>{activatedName || name}</span>- </span>+ <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>+ {displayName && (+ <span className={styles.chip}>+ <SkillsIcon className={styles.skillIcon} size={12} />+ <span className={styles.skillName}>{displayName}</span>+ </span>+ )}</div>);});diff --git a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsxindex a74c6fb3a11..fe8cfb04f20 100644--- a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx+++ b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx@@ -1,24 +1,59 @@'use client';import { type BuiltinInspectorProps } from '@lobechat/types';-import { cx } from 'antd-style';+import { SkillsIcon } from '@lobehub/ui/icons';+import { createStaticStyles, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ActivateSkillParams, ActivateSkillState } from '../../../types';+const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ gap: 6px;+ align-items: center;++ min-width: 0;+ max-width: 100%;+ margin-inline-start: 6px;+ padding-block: 3px;+ padding-inline: 10px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 999px;++ background: ${cssVar.colorBgContainer};+ `,+ skillIcon: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextDescription};+ `,+ skillName: css`+ overflow: hidden;++ min-width: 0;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));+export const RunSkillInspector = memo<BuiltinInspectorProps<ActivateSkillParams, ActivateSkillState>>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {const { t } = useTranslation('plugin');- const name = args?.name || partialArgs?.name || '';- const activatedName = pluginState?.name;+ const name = args?.name || partialArgs?.name;+ const displayName = pluginState?.name || name;if (isArgumentsStreaming) {- if (!name)+ if (!displayName)return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-skills.apiName.activateSkill')}</span>@@ -28,17 +63,23 @@ export const RunSkillInspector = memo<return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>- <span>{name}</span>+ <span className={styles.chip}>+ <SkillsIcon className={styles.skillIcon} size={12} />+ <span className={styles.skillName}>{displayName}</span>+ </span></div>);}return (<div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span>- <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>- <span className={highlightTextStyles.primary}>{activatedName || name}</span>- </span>+ <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>+ {displayName && (+ <span className={styles.chip}>+ <SkillsIcon className={styles.skillIcon} size={12} />+ <span className={styles.skillName}>{displayName}</span>+ </span>+ )}</div>);});diff --git a/packages/builtin-tools/src/inspectors.ts b/packages/builtin-tools/src/inspectors.tsindex d8df6870cb4..5db4f790aa4 100644--- a/packages/builtin-tools/src/inspectors.ts+++ b/packages/builtin-tools/src/inspectors.ts@@ -48,6 +48,7 @@ import {WebBrowsingInspectors,WebBrowsingManifest,} from '@lobechat/builtin-tool-web-browsing/client';+import { createRunCommandInspector } from '@lobechat/shared-tool-ui/inspectors';import { type BuiltinInspector } from '@lobechat/types';/**@@ -86,6 +87,9 @@ const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> =[SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,+ codex: {+ command_execution: createRunCommandInspector('Run') as BuiltinInspector,+ },};/**diff --git a/packages/builtin-tools/src/renders.ts b/packages/builtin-tools/src/renders.tsindex a4446e0cdd7..6da8c7eecf4 100644--- a/packages/builtin-tools/src/renders.ts+++ b/packages/builtin-tools/src/renders.ts@@ -33,6 +33,7 @@ import {WebBrowsingManifest,WebBrowsingRenders,} from '@lobechat/builtin-tool-web-browsing/client';+import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';import { type BuiltinRender } from '@lobechat/types';/**@@ -59,6 +60,9 @@ const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {// @deprecated backward compat: old messages stored 'lobe-tools' as identifier['lobe-tools']: LobeActivatorRenders as Record<string, BuiltinRender>,[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,+ codex: {+ command_execution: RunCommandRender as BuiltinRender,+ },};/**diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsnew file mode 100644index 00000000000..f1512f9fdc1--- /dev/null+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -0,0 +1,48 @@+export const CLAUDE_CODE_CLI_INSTALL_DOCS_URL =+ 'https://docs.anthropic.com/en/docs/claude-code/setup';++export const CLAUDE_CODE_CLI_INSTALL_COMMANDS = [+ 'curl -fsSL https://claude.ai/install.sh | bash',+ 'brew install --cask claude-code',+] as const;++export const CODEX_CLI_INSTALL_DOCS_URL =+ 'https://github.com/openai/codex#installing-and-running-codex-cli';++export const CODEX_CLI_INSTALL_COMMANDS = [+ 'npm install -g @openai/codex',+ 'brew install --cask codex',+] as const;++export const HeterogeneousAgentSessionErrorCode = {+ AuthRequired: 'auth_required',+ CliNotFound: 'cli_not_found',+ RateLimit: 'rate_limit',+ ResumeCwdMismatch: 'resume_cwd_mismatch',+ ResumeThreadNotFound: 'resume_thread_not_found',+} as const;++export type HeterogeneousAgentSessionErrorCode =+ (typeof HeterogeneousAgentSessionErrorCode)[keyof typeof HeterogeneousAgentSessionErrorCode];++export interface HeterogeneousAgentRateLimitInfo {+ isUsingOverage?: boolean;+ overageDisabledReason?: string;+ overageStatus?: string;+ rateLimitType?: string;+ resetsAt?: number;+ status?: string;+}++export interface HeterogeneousAgentSessionError {+ agentType?: string;+ code?: HeterogeneousAgentSessionErrorCode | string;+ command?: string;+ docsUrl?: string;+ installCommands?: readonly string[];+ message: string;+ rateLimitInfo?: HeterogeneousAgentRateLimitInfo;+ resumeSessionId?: string;+ stderr?: string;+ workingDirectory?: string;+}diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.tsindex 6ab68ba5638..492e21435c0 100644--- a/packages/electron-client-ipc/src/types/index.ts+++ b/packages/electron-client-ipc/src/types/index.ts@@ -1,5 +1,6 @@export * from './dataSync';export * from './git';+export * from './heterogeneousAgent';export * from './localSystem';export * from './mcpInstall';export * from './notification';diff --git a/packages/electron-client-ipc/src/types/toolDetector.ts b/packages/electron-client-ipc/src/types/toolDetector.tsindex f833010f9a0..438aba07401 100644--- a/packages/electron-client-ipc/src/types/toolDetector.ts+++ b/packages/electron-client-ipc/src/types/toolDetector.ts@@ -23,6 +23,13 @@ export interface ToolInfo {priority?: number;}+export type HeterogeneousCliAgentType = 'claude-code' | 'codex';++export interface DetectHeterogeneousAgentCommandParams {+ agentType: HeterogeneousCliAgentType;+ command: string;+}+/*** Claude Code CLI auth status (from `claude auth status --json`)*/diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex be1331b22b4..4b1bc06410f 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -2,13 +2,18 @@"name": "@lobechat/heterogeneous-agents","version": "1.0.0","private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts"+ },"main": "./src/index.ts","scripts": {"test": "vitest","test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {- "@lobechat/builtin-tool-claude-code": "workspace:*"+ "@lobechat/builtin-tool-claude-code": "workspace:*",+ "@lobehub/icons": "^5.4.0"},"devDependencies": {"@lobechat/types": "workspace:*"diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 89d06beac0d..b2475e5b4a3 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -32,6 +32,71 @@ describe('ClaudeCodeAdapter', () => {expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);expect(events[1].data.message).toBe('boom');});++ it('classifies auth failures from failed result events', () => {+ const adapter = new ClaudeCodeAdapter();+ const rawError =+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({ is_error: true, result: rawError, type: 'result' });++ expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);+ expect(events[1].data).toMatchObject({+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: 'auth_required',+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ stderr: rawError,+ });+ expect(events[1].data.message).toBe(+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ );+ });++ it('classifies rate-limit failures from paired rate_limit_event + result events', () => {+ const adapter = new ClaudeCodeAdapter();+ const rawError = "You've hit your limit · resets 9am (Asia/Shanghai)";++ adapter.adapt({ subtype: 'init', type: 'system' });+ expect(+ adapter.adapt({+ rate_limit_info: {+ isUsingOverage: false,+ overageDisabledReason: 'org_level_disabled',+ overageStatus: 'rejected',+ rateLimitType: 'seven_day',+ resetsAt: 1_776_992_400,+ status: 'rejected',+ },+ type: 'rate_limit_event',+ }),+ ).toEqual([]);++ const events = adapter.adapt({+ api_error_status: 429,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);+ expect(events[1].data).toMatchObject({+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: 'rate_limit',+ message: rawError,+ rateLimitInfo: {+ isUsingOverage: false,+ overageDisabledReason: 'org_level_disabled',+ overageStatus: 'rejected',+ rateLimitType: 'seven_day',+ resetsAt: 1_776_992_400,+ status: 'rejected',+ },+ stderr: rawError,+ });+ });});describe('content mapping', () => {@@ -838,9 +903,9 @@ describe('ClaudeCodeAdapter', () => {expect(adapter.adapt('string')).toEqual([]);});- it('returns empty array for unknown event types (rate_limit_event)', () => {+ it('returns empty array for unknown event types', () => {const adapter = new ClaudeCodeAdapter();- const events = adapter.adapt({ type: 'rate_limit_event', data: {} });+ const events = adapter.adapt({ type: 'something_unexpected', data: {} });expect(events).toEqual([]);});diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 627bfd2be18..a6be01e52f1 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -13,7 +13,7 @@* {type: 'user', message: {content: [{type: 'tool_result', tool_use_id, content}]}}* {type: 'assistant', message: {id: <NEW>, content: [{type: 'text', text}], ...}}* {type: 'result', is_error, result, ...}- * {type: 'rate_limit_event', ...} (ignored)+ * {type: 'rate_limit_event', ...}** With `--include-partial-messages` (enabled by default in this adapter), CC* also emits token-level deltas wrapped as:@@ -44,6 +44,8 @@ import type {AgentCLIPreset,AgentEventAdapter,HeterogeneousAgentEvent,+ HeterogeneousRateLimitInfo,+ HeterogeneousTerminalErrorData,StreamChunkData,SubagentEventContext,ToolCallPayload,@@ -51,6 +53,97 @@ import type {UsageData,} from '../types';+const CLAUDE_CODE_CLI_INSTALL_DOCS_URL = 'https://docs.anthropic.com/en/docs/claude-code/setup';++const CLI_AUTH_REQUIRED_PATTERNS = [+ /failed to authenticate/i,+ /invalid authentication credentials/i,+ /authentication[_ ]error/i,+ /not authenticated/i,+ /\bunauthorized\b/i,+ /\b401\b/,+] as const;++const CLI_RATE_LIMIT_PATTERNS = [/you'?ve hit your limit/i, /rate limit/i] as const;++const getCliResultMessage = (result: unknown): string | undefined => {+ if (typeof result === 'string') return result;+ if (+ result &&+ typeof result === 'object' &&+ 'message' in result &&+ typeof result.message === 'string'+ ) {+ return result.message;+ }++ try {+ return result == null ? undefined : JSON.stringify(result);+ } catch {+ return undefined;+ }+};++const getAuthRequiredTerminalError = (+ result: unknown,+): HeterogeneousTerminalErrorData | undefined => {+ const rawMessage = getCliResultMessage(result);+ if (!rawMessage || !CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(rawMessage))) {+ return;+ }++ return {+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: 'auth_required',+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ error: rawMessage,+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr: rawMessage,+ };+};++const toRateLimitInfo = (value: unknown): HeterogeneousRateLimitInfo | undefined => {+ if (!value || typeof value !== 'object') return;++ const raw = value as Record<string, unknown>;++ return {+ isUsingOverage: typeof raw.isUsingOverage === 'boolean' ? raw.isUsingOverage : undefined,+ overageDisabledReason:+ typeof raw.overageDisabledReason === 'string' ? raw.overageDisabledReason : undefined,+ overageStatus: typeof raw.overageStatus === 'string' ? raw.overageStatus : undefined,+ rateLimitType: typeof raw.rateLimitType === 'string' ? raw.rateLimitType : undefined,+ resetsAt: typeof raw.resetsAt === 'number' ? raw.resetsAt : undefined,+ status: typeof raw.status === 'string' ? raw.status : undefined,+ };+};++const getRateLimitTerminalError = (+ result: unknown,+ rateLimitInfo?: HeterogeneousRateLimitInfo,+ apiErrorStatus?: unknown,+): HeterogeneousTerminalErrorData | undefined => {+ const rawMessage = getCliResultMessage(result);+ const looksLikeRateLimit =+ apiErrorStatus === 429 ||+ !!rateLimitInfo ||+ (!!rawMessage && CLI_RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(rawMessage)));++ if (!looksLikeRateLimit || !rawMessage) return;++ return {+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: 'rate_limit',+ error: rawMessage,+ message: rawMessage,+ rateLimitInfo,+ stderr: rawMessage,+ };+};+/*** CC's TodoWrite is a declarative state-write tool: its `tool_use.input` IS* the target todos list, and the `tool_result` content is just a confirmation@@ -140,6 +233,7 @@ export const claudeCodePreset: AgentCLIPreset = {export class ClaudeCodeAdapter implements AgentEventAdapter {sessionId?: string;+ private pendingRateLimitInfo?: HeterogeneousRateLimitInfo;/** Pending tool_use ids awaiting their tool_result */private pendingToolCalls = new Set<string>();@@ -201,6 +295,9 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {if (!raw || typeof raw !== 'object') return [];switch (raw.type) {+ case 'rate_limit_event': {+ return this.handleRateLimitEvent(raw);+ }case 'system': {return this.handleSystem(raw);}@@ -218,7 +315,7 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {}default: {return [];- } // rate_limit_event, etc.+ }}}@@ -246,6 +343,12 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {}private handleAssistant(raw: any): HeterogeneousAgentEvent[] {+ // Claude Code emits a synthetic assistant text turn for rate-limit+ // failures. We already surface the structured rate-limit metadata via+ // the paired `rate_limit_event` + terminal `result`, so letting this+ // text through would momentarily render a duplicate plain-text bubble.+ if (raw.error === 'rate_limit') return [];+const content = raw.message?.content;if (!Array.isArray(content)) return [];@@ -328,6 +431,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {return events;}+ private handleRateLimitEvent(raw: any): HeterogeneousAgentEvent[] {+ this.pendingRateLimitInfo = toRateLimitInfo(raw.rate_limit_info);+ return [];+ }+/*** Handle a subagent assistant event (tagged with `parent_tool_use_id`).*@@ -604,13 +712,25 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {);}+ const resultMessage = getCliResultMessage(raw.result) || 'Agent execution failed';+ const rateLimitError = getRateLimitTerminalError(+ raw.result,+ this.pendingRateLimitInfo,+ raw.api_error_status,+ );const finalEvent: HeterogeneousAgentEvent = raw.is_error- ? this.makeEvent('error', {- error: raw.result || 'Agent execution failed',- message: raw.result || 'Agent execution failed',- })+ ? this.makeEvent(+ 'error',+ rateLimitError ||+ getAuthRequiredTerminalError(raw.result) || {+ error: resultMessage,+ message: resultMessage,+ },+ ): this.makeEvent('agent_runtime_end', {});+ this.pendingRateLimitInfo = undefined;+return [...events, this.makeEvent('stream_end', {}), finalEvent];}diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.tsnew file mode 100644index 00000000000..445edd8b151--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts@@ -0,0 +1,356 @@+import { describe, expect, it } from 'vitest';++import { CodexAdapter } from './codex';++describe('CodexAdapter', () => {+ it('captures the session id from thread.started', () => {+ const adapter = new CodexAdapter();++ const events = adapter.adapt({+ thread_id: 'thread-123',+ type: 'thread.started',+ });++ expect(events).toHaveLength(0);+ expect(adapter.sessionId).toBe('thread-123');+ });++ it('emits stream start and text chunks for turn + agent messages', () => {+ const adapter = new CodexAdapter();++ const start = adapter.adapt({ type: 'turn.started' });+ const text = adapter.adapt({+ item: {+ id: 'item_0',+ text: 'hello from codex',+ type: 'agent_message',+ },+ type: 'item.completed',+ });++ expect(start[0]).toMatchObject({+ data: { provider: 'codex' },+ type: 'stream_start',+ });+ expect(text[0]).toMatchObject({+ data: { chunkType: 'text', content: 'hello from codex' },+ type: 'stream_chunk',+ });+ });++ it('emits a new-step boundary when a second turn starts', () => {+ const adapter = new CodexAdapter();++ const firstTurn = adapter.adapt({ type: 'turn.started' });+ const secondTurn = adapter.adapt({ type: 'turn.started' });++ expect(firstTurn).toHaveLength(1);+ expect(firstTurn[0]).toMatchObject({+ data: { provider: 'codex' },+ stepIndex: 0,+ type: 'stream_start',+ });++ expect(secondTurn).toHaveLength(2);+ expect(secondTurn[0]).toMatchObject({+ data: {},+ stepIndex: 1,+ type: 'stream_end',+ });+ expect(secondTurn[1]).toMatchObject({+ data: { newStep: true, provider: 'codex' },+ stepIndex: 1,+ type: 'stream_start',+ });+ });++ it('emits a new-step boundary when a later agent_message item arrives in the same turn', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({ type: 'turn.started' });+ adapter.adapt({+ item: {+ id: 'item_0',+ text: 'Running the first checks.',+ type: 'agent_message',+ },+ type: 'item.completed',+ });+ adapter.adapt({+ item: {+ command: '/bin/zsh -lc pwd',+ id: 'item_1',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });+ adapter.adapt({+ item: {+ aggregated_output: '/repo\\n',+ command: '/bin/zsh -lc pwd',+ exit_code: 0,+ id: 'item_1',+ status: 'completed',+ type: 'command_execution',+ },+ type: 'item.completed',+ });++ const secondMessage = adapter.adapt({+ item: {+ id: 'item_2',+ text: 'Now I will inspect the branch.',+ type: 'agent_message',+ },+ type: 'item.completed',+ });++ expect(secondMessage).toHaveLength(3);+ expect(secondMessage[0]).toMatchObject({+ data: {},+ stepIndex: 1,+ type: 'stream_end',+ });+ expect(secondMessage[1]).toMatchObject({+ data: { newStep: true, provider: 'codex' },+ stepIndex: 1,+ type: 'stream_start',+ });+ expect(secondMessage[2]).toMatchObject({+ data: { chunkType: 'text', content: 'Now I will inspect the branch.' },+ stepIndex: 1,+ type: 'stream_chunk',+ });+ });++ it('maps command execution items into tool lifecycle events', () => {+ const adapter = new CodexAdapter();++ const started = adapter.adapt({+ item: {+ command: '/bin/zsh -lc pwd',+ id: 'item_1',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });+ const completed = adapter.adapt({+ item: {+ aggregated_output: '/tmp\\n',+ command: '/bin/zsh -lc pwd',+ exit_code: 0,+ id: 'item_1',+ status: 'completed',+ type: 'command_execution',+ },+ type: 'item.completed',+ });++ expect(started).toHaveLength(2);+ expect(started[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'command_execution',+ id: 'item_1',+ identifier: 'codex',+ },+ ],+ },+ type: 'stream_chunk',+ });+ expect(started[1]).toMatchObject({+ data: { toolCallId: 'item_1' },+ type: 'tool_start',+ });++ expect(completed).toHaveLength(2);+ expect(completed[0]).toMatchObject({+ data: {+ content: '/tmp\\n',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: '/tmp\\n',+ stdout: '/tmp\\n',+ success: true,+ },+ toolCallId: 'item_1',+ },+ type: 'tool_result',+ });+ expect(completed[1]).toMatchObject({+ data: { isSuccess: true, toolCallId: 'item_1' },+ type: 'tool_end',+ });+ });++ it('emits cumulative tools_calling within the same Codex step', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({ type: 'turn.started' });++ const firstTool = adapter.adapt({+ item: {+ command: '/bin/zsh -lc pwd',+ id: 'item_1',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });+ const secondTool = adapter.adapt({+ item: {+ command: "/bin/zsh -lc 'git status --short'",+ id: 'item_2',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });++ expect(firstTool[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'item_1' }],+ },+ type: 'stream_chunk',+ });+ expect(secondTool[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'item_1' }, { id: 'item_2' }],+ },+ type: 'stream_chunk',+ });+ expect(secondTool[1]).toMatchObject({+ data: { toolCallId: 'item_2' },+ type: 'tool_start',+ });+ });++ it('resets cumulative tools_calling after a same-turn agent_message step boundary', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({ type: 'turn.started' });+ adapter.adapt({+ item: {+ id: 'item_0',+ text: 'Running the first checks.',+ type: 'agent_message',+ },+ type: 'item.completed',+ });+ adapter.adapt({+ item: {+ command: '/bin/zsh -lc pwd',+ id: 'item_1',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });+ adapter.adapt({+ item: {+ id: 'item_2',+ text: 'Now I will inspect the branch.',+ type: 'agent_message',+ },+ type: 'item.completed',+ });++ const nextStepTool = adapter.adapt({+ item: {+ command: "/bin/zsh -lc 'git branch --show-current'",+ id: 'item_3',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });++ expect(nextStepTool[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'item_3' }],+ },+ stepIndex: 1,+ type: 'stream_chunk',+ });+ });++ it('maps turn.completed usage into turn metadata', () => {+ const adapter = new CodexAdapter();++ const events = adapter.adapt({+ type: 'turn.completed',+ usage: {+ cached_input_tokens: 4,+ input_tokens: 10,+ output_tokens: 3,+ },+ });++ expect(events[0]).toMatchObject({+ data: {+ phase: 'turn_metadata',+ provider: 'codex',+ usage: {+ inputCachedTokens: 4,+ inputCacheMissTokens: 10,+ totalInputTokens: 14,+ totalOutputTokens: 3,+ totalTokens: 17,+ },+ },+ type: 'step_complete',+ });+ });++ it('hydrates turn metadata model from session_configured when turn.completed omits it', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({+ model: 'gpt-5.3-codex',+ type: 'session_configured',+ });++ const events = adapter.adapt({+ type: 'turn.completed',+ usage: {+ input_tokens: 10,+ output_tokens: 3,+ },+ });++ expect(events[0]).toMatchObject({+ data: {+ model: 'gpt-5.3-codex',+ phase: 'turn_metadata',+ provider: 'codex',+ },+ type: 'step_complete',+ });+ });++ it('emits turn metadata when turn.completed reports a model without usage', () => {+ const adapter = new CodexAdapter();++ const events = adapter.adapt({+ model: 'gpt-5.4',+ type: 'turn.completed',+ });++ expect(events[0]).toMatchObject({+ data: {+ model: 'gpt-5.4',+ phase: 'turn_metadata',+ provider: 'codex',+ },+ type: 'step_complete',+ });+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.tsnew file mode 100644index 00000000000..e1bf1636f40--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/codex.ts@@ -0,0 +1,294 @@+import type {+ AgentCLIPreset,+ AgentEventAdapter,+ HeterogeneousAgentEvent,+ StepCompleteData,+ ToolCallPayload,+ ToolResultData,+ UsageData,+} from '../types';++const CODEX_IDENTIFIER = 'codex';+const CODEX_COMMAND_API = 'command_execution';++interface CodexCommandExecutionItem {+ aggregated_output?: string;+ command?: string;+ exit_code?: number | null;+ id: string;+ status?: string;+ type: string;+}++const toUsageData = (+ raw:+ | {+ cached_input_tokens?: number;+ input_tokens?: number;+ output_tokens?: number;+ }+ | null+ | undefined,+): UsageData | undefined => {+ if (!raw) return undefined;++ const inputCacheMissTokens = raw.input_tokens || 0;+ const inputCachedTokens = raw.cached_input_tokens || 0;+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens;+ const totalOutputTokens = raw.output_tokens || 0;++ if (totalInputTokens + totalOutputTokens === 0) return undefined;++ return {+ inputCachedTokens: inputCachedTokens || undefined,+ inputCacheMissTokens,+ totalInputTokens,+ totalOutputTokens,+ totalTokens: totalInputTokens + totalOutputTokens,+ };+};++const toToolPayload = (item: CodexCommandExecutionItem): ToolCallPayload => ({+ apiName: item.type || CODEX_COMMAND_API,+ arguments: JSON.stringify(+ item.type === CODEX_COMMAND_API ? { command: item.command || '' } : item,+ ),+ id: item.id,+ identifier: CODEX_IDENTIFIER,+ type: 'default',+});++const getToolContent = (item: CodexCommandExecutionItem): string => {+ if (typeof item.aggregated_output === 'string') return item.aggregated_output;+ return '';+};++const getToolResultData = (item: CodexCommandExecutionItem): ToolResultData => {+ const exitCode = item.exit_code ?? undefined;+ const output = getToolContent(item);+ const isSuccess = item.status === 'completed' && (exitCode === undefined || exitCode === 0);++ return {+ content: output,+ isError: !isSuccess,+ pluginState: {+ ...(exitCode !== undefined ? { exitCode } : {}),+ ...(isSuccess ? {} : { error: output || `Command failed (${exitCode ?? 'unknown'})` }),+ isBackground: false,+ output,+ stdout: output,+ success: isSuccess,+ },+ toolCallId: item.id,+ };+};++const getEventModel = (raw: any): string | undefined => {+ const candidates = [+ raw?.model,+ raw?.session?.model,+ raw?.sessionMeta?.model,+ raw?.session_meta?.model,+ raw?.turn?.model,+ raw?.turn_context?.model,+ ];++ return candidates.find((candidate): candidate is string => typeof candidate === 'string');+};++export const codexPreset: AgentCLIPreset = {+ baseArgs: ['exec', '--json', '--skip-git-repo-check', '--full-auto'],+ promptMode: 'stdin',+ resumeArgs: (sessionId) => ['exec', 'resume', '--json', '--skip-git-repo-check', sessionId],+};++export class CodexAdapter implements AgentEventAdapter {+ private currentAgentMessageItemId?: string;+ private currentModel?: string;+ sessionId?: string;++ private hasStepActivity = false;+ private pendingToolCalls = new Set<string>();+ private stepToolCalls: ToolCallPayload[] = [];+ private stepToolCallIds = new Set<string>();+ private started = false;+ private stepIndex = 0;++ adapt(raw: any): HeterogeneousAgentEvent[] {+ if (!raw || typeof raw !== 'object') return [];++ switch (raw.type) {+ case 'thread.started': {+ this.sessionId = raw.thread_id;+ return [];+ }+ case 'turn.started': {+ return this.handleTurnStarted();+ }+ case 'session.configured':+ case 'session_configured': {+ return this.handleSessionConfigured(raw);+ }+ case 'turn.completed': {+ return this.handleTurnCompleted(raw);+ }+ case 'item.started': {+ return this.handleItemStarted(raw.item);+ }+ case 'item.completed': {+ return this.handleItemCompleted(raw.item);+ }+ default: {+ return [];+ }+ }+ }++ flush(): HeterogeneousAgentEvent[] {+ const events = [...this.pendingToolCalls].map((toolCallId) =>+ this.makeEvent('tool_end', {+ isSuccess: false,+ toolCallId,+ }),+ );++ this.pendingToolCalls.clear();+ return events;+ }++ private handleTurnCompleted(raw: any): HeterogeneousAgentEvent[] {+ const model = getEventModel(raw) || this.currentModel;+ if (model) this.currentModel = model;++ const usage = toUsageData(raw.usage);+ if (!usage && !model) return [];++ const data: StepCompleteData = {+ ...(model ? { model } : {}),+ phase: 'turn_metadata',+ provider: CODEX_IDENTIFIER,+ ...(usage ? { usage } : {}),+ };++ return [this.makeEvent('step_complete', data)];+ }++ private handleSessionConfigured(raw: any): HeterogeneousAgentEvent[] {+ const model = getEventModel(raw);+ if (model) this.currentModel = model;++ return [];+ }++ private handleTurnStarted(): HeterogeneousAgentEvent[] {+ this.currentAgentMessageItemId = undefined;+ this.hasStepActivity = false;+ this.resetStepToolCalls();++ if (!this.started) {+ this.started = true;+ return [this.makeEvent('stream_start', { provider: CODEX_IDENTIFIER })];+ }++ this.stepIndex += 1;+ return [+ this.makeEvent('stream_end', {}),+ this.makeEvent('stream_start', { newStep: true, provider: CODEX_IDENTIFIER }),+ ];+ }++ private handleItemStarted(item: any): HeterogeneousAgentEvent[] {+ if (!item?.id || !item?.type || item.type === 'agent_message') return [];++ this.hasStepActivity = true;++ const tool = toToolPayload(item);+ this.pendingToolCalls.add(tool.id);++ return this.emitToolChunk(tool);+ }++ private handleItemCompleted(item: any): HeterogeneousAgentEvent[] {+ if (!item?.type) return [];++ if (item.type === 'agent_message') {+ if (!item.text) return [];++ const events: HeterogeneousAgentEvent[] = [];+ const shouldStartNewStep =+ this.hasStepActivity && !!item.id && item.id !== this.currentAgentMessageItemId;++ if (shouldStartNewStep) {+ this.stepIndex += 1;+ this.resetStepToolCalls();+ events.push(this.makeEvent('stream_end', {}));+ events.push(this.makeEvent('stream_start', { newStep: true, provider: CODEX_IDENTIFIER }));+ }++ this.currentAgentMessageItemId = item.id;+ this.hasStepActivity = true;+ events.push(+ this.makeEvent('stream_chunk', {+ chunkType: 'text',+ content: item.text,+ }),+ );++ return events;+ }++ if (!item.id) return [];++ const events: HeterogeneousAgentEvent[] = [];++ if (!this.pendingToolCalls.has(item.id)) {+ const tool = toToolPayload(item);+ events.push(...this.emitToolChunk(tool));+ }++ this.pendingToolCalls.delete(item.id);+ this.hasStepActivity = true;+ events.push(this.makeEvent('tool_result', getToolResultData(item)));+ events.push(+ this.makeEvent('tool_end', {+ isSuccess:+ item.status === 'completed' &&+ (item.exit_code === null || item.exit_code === undefined || item.exit_code === 0),+ toolCallId: item.id,+ }),+ );++ return events;+ }++ private emitToolChunk(tool: ToolCallPayload): HeterogeneousAgentEvent[] {+ if (!this.stepToolCallIds.has(tool.id)) {+ this.stepToolCallIds.add(tool.id);+ this.stepToolCalls.push(tool);+ }++ return [+ this.makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: [...this.stepToolCalls],+ }),+ this.makeEvent('tool_start', {+ toolCallId: tool.id,+ }),+ ];+ }++ private resetStepToolCalls(): void {+ this.stepToolCalls = [];+ this.stepToolCallIds.clear();+ }++ private makeEvent(type: HeterogeneousAgentEvent['type'], data: any): HeterogeneousAgentEvent {+ return {+ data,+ stepIndex: this.stepIndex,+ timestamp: Date.now(),+ type,+ };+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex 94b6a4e7678..473b0ed3ef0 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -1 +1,2 @@export { ClaudeCodeAdapter, claudeCodePreset } from './claudeCode';+export { CodexAdapter, codexPreset } from './codex';diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsnew file mode 100644index 00000000000..0e4e68bc2b0--- /dev/null+++ b/packages/heterogeneous-agents/src/client/index.ts@@ -0,0 +1,42 @@+import type { IconType } from '@lobehub/icons';+import { ClaudeCode, Codex, getLobeIconCDN } from '@lobehub/icons';++import {+ getHeterogeneousAgentConfig,+ HETEROGENEOUS_AGENT_CONFIGS,+ type HeterogeneousAgentConfig,+} from '../config';++export interface HeterogeneousAgentClientConfig extends HeterogeneousAgentConfig {+ avatar: string;+ icon: IconType;+}++const heterogeneousAgentIcons = {+ 'claude-code': ClaudeCode,+ 'codex': Codex,+} as const satisfies Record<HeterogeneousAgentConfig['type'], IconType>;++const createAgentAvatar = (iconId: string) =>+ getLobeIconCDN(iconId, {+ cdn: 'aliyun',+ format: 'avatar',+ });++export const HETEROGENEOUS_AGENT_CLIENT_CONFIGS = HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({+ ...config,+ avatar: createAgentAvatar(config.iconId),+ icon: heterogeneousAgentIcons[config.type],+})) as readonly HeterogeneousAgentClientConfig[];++export const getHeterogeneousAgentClientConfig = (type: HeterogeneousAgentConfig['type']) => {+ const config = getHeterogeneousAgentConfig(type);++ if (!config) return undefined;++ return {+ ...config,+ avatar: createAgentAvatar(config.iconId),+ icon: heterogeneousAgentIcons[config.type],+ } satisfies HeterogeneousAgentClientConfig;+};diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsnew file mode 100644index 00000000000..c3030f0ba68--- /dev/null+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { getHeterogeneousAgentConfig, HETEROGENEOUS_AGENT_CONFIGS } from './config';+import { HETEROGENEOUS_TYPE_LABELS } from './labels';++describe('heterogeneous agent config', () => {+ it('defines create config for all registered agent types', () => {+ expect(HETEROGENEOUS_AGENT_CONFIGS.map((config) => config.type)).toEqual([+ 'claude-code',+ 'codex',+ ]);+ });++ it('resolves config by type', () => {+ expect(getHeterogeneousAgentConfig('claude-code')).toMatchObject({+ command: 'claude',+ title: 'Claude Code',+ type: 'claude-code',+ });+ expect(getHeterogeneousAgentConfig('codex')).toMatchObject({+ command: 'codex',+ title: 'Codex',+ type: 'codex',+ });+ });++ it('derives display labels from the shared config source', () => {+ expect(HETEROGENEOUS_TYPE_LABELS).toEqual({+ 'claude-code': 'Claude Code',+ 'codex': 'Codex',+ });+ });+});diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.tsnew file mode 100644index 00000000000..ab9e66ac14c--- /dev/null+++ b/packages/heterogeneous-agents/src/config.ts@@ -0,0 +1,34 @@+import type { HeterogeneousProviderConfig } from '@lobechat/types';++export type HeterogeneousAgentMenuLabelKey = 'newClaudeCodeAgent' | 'newCodexAgent';++export interface HeterogeneousAgentConfig {+ command: string;+ iconId: string;+ menuKey: string;+ menuLabelKey: HeterogeneousAgentMenuLabelKey;+ title: string;+ type: HeterogeneousProviderConfig['type'];+}++export const HETEROGENEOUS_AGENT_CONFIGS = [+ {+ command: 'claude',+ iconId: 'ClaudeCode',+ menuKey: 'newClaudeCodeAgent',+ menuLabelKey: 'newClaudeCodeAgent',+ title: 'Claude Code',+ type: 'claude-code',+ },+ {+ command: 'codex',+ iconId: 'Codex',+ menuKey: 'newCodexAgent',+ menuLabelKey: 'newCodexAgent',+ title: 'Codex',+ type: 'codex',+ },+] as const satisfies readonly HeterogeneousAgentConfig[];++export const getHeterogeneousAgentConfig = (type: HeterogeneousProviderConfig['type']) =>+ HETEROGENEOUS_AGENT_CONFIGS.find((config) => config.type === type);diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 745e43a197a..7aaa575b3f9 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -1,4 +1,5 @@export { ClaudeCodeAdapter, claudeCodePreset } from './adapters';+export { getHeterogeneousAgentConfig, HETEROGENEOUS_AGENT_CONFIGS } from './config';export { HETEROGENEOUS_TYPE_LABELS } from './labels';export { createAdapter, getPreset, listAgentTypes } from './registry';export type {@@ -7,6 +8,7 @@ export type {AgentProcessConfig,HeterogeneousAgentEvent,HeterogeneousEventType,+ HeterogeneousTerminalErrorData,StreamChunkData,StreamChunkType,StreamStartData,diff --git a/packages/heterogeneous-agents/src/labels.ts b/packages/heterogeneous-agents/src/labels.tsindex fd6e85f1758..09175a7e763 100644--- a/packages/heterogeneous-agents/src/labels.ts+++ b/packages/heterogeneous-agents/src/labels.ts@@ -1,3 +1,5 @@+import { HETEROGENEOUS_AGENT_CONFIGS } from './config';+/*** Display-name mapping for heterogeneous agent types.*@@ -5,7 +7,6 @@* use this to render user-facing names (e.g. "Claude Code is running")* without knowing adapter-specific branding.*/-export const HETEROGENEOUS_TYPE_LABELS: Record<string, string> = {- 'claude-code': 'Claude Code',- 'codex': 'Codex',-};+export const HETEROGENEOUS_TYPE_LABELS: Record<string, string> = Object.fromEntries(+ HETEROGENEOUS_AGENT_CONFIGS.map((config) => [config.type, config.title]),+);diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.tsindex ef825c224f4..e20954c847a 100644--- a/packages/heterogeneous-agents/src/registry.test.ts+++ b/packages/heterogeneous-agents/src/registry.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { ClaudeCodeAdapter } from './adapters';+import { ClaudeCodeAdapter, CodexAdapter } from './adapters';import { createAdapter, getPreset, listAgentTypes } from './registry';describe('registry', () => {@@ -10,6 +10,11 @@ describe('registry', () => {expect(adapter).toBeInstanceOf(ClaudeCodeAdapter);});+ it('creates a CodexAdapter for "codex"', () => {+ const adapter = createAdapter('codex');+ expect(adapter).toBeInstanceOf(CodexAdapter);+ });+it('throws for unknown agent type', () => {expect(() => createAdapter('unknown-agent')).toThrow('Unknown agent type: "unknown-agent"');});@@ -33,6 +38,13 @@ describe('registry', () => {expect(args).toContain('sess_abc');});+ it('returns preset with exec args for codex', () => {+ const preset = getPreset('codex');+ expect(preset.baseArgs).toContain('exec');+ expect(preset.baseArgs).toContain('--json');+ expect(preset.promptMode).toBe('stdin');+ });+it('throws for unknown agent type', () => {expect(() => getPreset('nope')).toThrow('Unknown agent type: "nope"');});@@ -42,6 +54,7 @@ describe('registry', () => {it('includes claude-code', () => {const types = listAgentTypes();expect(types).toContain('claude-code');+ expect(types).toContain('codex');});});});diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex bbed35ffe3d..f71ea87a905 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -5,7 +5,7 @@* New agents are added by registering here — no other code changes needed.*/-import { ClaudeCodeAdapter, claudeCodePreset } from './adapters';+import { ClaudeCodeAdapter, claudeCodePreset, CodexAdapter, codexPreset } from './adapters';import type { AgentCLIPreset, AgentEventAdapter } from './types';interface AgentRegistryEntry {@@ -18,8 +18,10 @@ const registry: Record<string, AgentRegistryEntry> = {createAdapter: () => new ClaudeCodeAdapter(),preset: claudeCodePreset,},- // Future:- // 'codex': { createAdapter: () => new CodexAdapter(), preset: codexPreset },+ 'codex': {+ createAdapter: () => new CodexAdapter(),+ preset: codexPreset,+ },// 'kimi-cli': { createAdapter: () => new KimiCLIAdapter(), preset: kimiPreset },};diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex 5cb18663e21..5a44cff015e 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -203,6 +203,33 @@ export interface StepCompleteData {usage?: UsageData;}+export interface HeterogeneousRateLimitInfo {+ isUsingOverage?: boolean;+ overageDisabledReason?: string;+ overageStatus?: string;+ rateLimitType?: string;+ resetsAt?: number;+ status?: string;+}++/**+ * Normalized terminal error payload emitted by adapters when the upstream CLI+ * exposes enough context to classify the failure. The executor can persist+ * this directly as a `ChatMessageError` body without re-parsing provider-+ * specific stderr shapes.+ */+export interface HeterogeneousTerminalErrorData {+ agentType?: string;+ clearEchoedContent?: boolean;+ code?: string;+ docsUrl?: string;+ error?: string;+ installCommands?: readonly string[];+ message: string;+ rateLimitInfo?: HeterogeneousRateLimitInfo;+ stderr?: string;+}+// ─── Adapter Interface ───/**diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex 6ff419ab0f4..d7f6329902e 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -11,7 +11,7 @@ export interface HeterogeneousProviderConfig {/** Custom environment variables */env?: Record<string, string>;/** Agent runtime type */- type: 'claude-code';+ type: 'claude-code' | 'codex';}/**diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex 4a312a3496f..2d385de4744 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -57,7 +57,7 @@ export interface SendMessageServerParams {* Message metadata (e.g., isSupervisor for group orchestration)*/metadata?: Record<string, unknown>;- model: string;+ model?: string;provider: string;};/**diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 014a0ce40cb..2970ada25f1 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -1,5 +1,6 @@import { isDesktop } from '@lobechat/const';import { HotkeyEnum, KeyEnum } from '@lobechat/const/hotkeys';+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import { chainInputCompletion } from '@lobechat/prompts';import { isCommandPressed, merge } from '@lobechat/utils';import { INSERT_MENTION_COMMAND, ReactAutoCompletePlugin, ReactMathPlugin } from '@lobehub/editor';@@ -110,7 +111,9 @@ const InputEditor = memo<{const heterogeneousType = useAgentStore((s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type,);- const heterogeneousName = heterogeneousType === 'claude-code' ? 'Claude Code' : undefined;+ const heterogeneousName = heterogeneousType+ ? (HETEROGENEOUS_TYPE_LABELS[heterogeneousType] ?? heterogeneousType)+ : undefined;// Heterogeneous agents (e.g. Claude Code) don't yet support @-assigning to other agentsconst showAgentAssignmentHint =!heterogeneousName && categories.some((category) => category.id === 'agent');diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxnew file mode 100644index 00000000000..52e0087e887--- /dev/null+++ b/src/features/Conversation/Error/index.test.tsx@@ -0,0 +1,166 @@+import type * as businessConstModule from '@lobechat/business-const';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import type * as modelRuntimeModule from '@lobechat/model-runtime';+import type * as lobechatTypesModule from '@lobechat/types';+import type * as lobehubUiModule from '@lobehub/ui';+import { render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { describe, expect, it, vi } from 'vitest';++import ErrorMessageExtra from './index';++const navigateMock = vi.fn();++vi.mock('@lobechat/business-const', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof businessConstModule;++ return {+ ...actual,+ ENABLE_BUSINESS_FEATURES: false,+ };+});++vi.mock('@lobechat/model-runtime', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof modelRuntimeModule;++ return {+ ...actual,+ AgentRuntimeErrorType: {+ ...actual.AgentRuntimeErrorType,+ AgentRuntimeError: 'AgentRuntimeError',+ },+ };+});++vi.mock('@lobechat/types', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof lobechatTypesModule;++ return {+ ...actual,+ ChatErrorType: {+ ...actual.ChatErrorType,+ SystemTimeNotMatchError: 'SystemTimeNotMatchError',+ },+ };+});++vi.mock('@lobehub/ui', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof lobehubUiModule;++ return {+ ...actual,+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Highlighter: ({ children }: { children?: ReactNode }) => <pre>{children}</pre>,+ Skeleton: {+ ...actual.Skeleton,+ Button: () => <div>loading</div>,+ },+ };+});++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('react-router-dom', () => ({+ useNavigate: () => navigateMock,+}));++vi.mock('@/business/client/hooks/useBusinessErrorAlertConfig', () => ({+ default: () => undefined,+}));++vi.mock('@/business/client/hooks/useBusinessErrorContent', () => ({+ default: () => ({ errorType: undefined, hideMessage: false }),+}));++vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () => ({+ default: () => undefined,+}));++vi.mock('@/features/Conversation/ChatItem/components/ErrorContent', () => ({+ default: ({ error }: { error?: { extra?: ReactNode; message?: string } }) => (+ <div>+ <div>{error?.message}</div>+ {error?.extra}+ </div>+ ),+}));++vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({+ default: ({ agentType, error }: { agentType?: string; error?: { code?: string } }) => (+ <div>{`guide:${agentType}:${error?.code}`}</div>+ ),+}));++vi.mock('@/hooks/useProviderName', () => ({+ useProviderName: () => 'Mock Provider',+}));++vi.mock('@/libs/next/dynamic', () => ({+ default: () => () => <div>dynamic</div>,+}));++describe('ErrorMessageExtra', () => {+ it('renders the auth guide when the refreshed error is missing type but still carries session code', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.undefined' }}+ data={{+ error: {+ body: {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ message: 'Failed to authenticate',+ },+ message: 'Failed to authenticate',+ } as any,+ id: 'msg-auth',+ }}+ />,+ );++ expect(screen.getByText('guide:claude-code:auth_required')).toBeInTheDocument();+ });++ it('renders the rate-limit guide when the refreshed error carries rate_limit code', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.undefined' }}+ data={{+ error: {+ body: {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.RateLimit,+ message: "You've hit your limit · resets 9am (Asia/Shanghai)",+ },+ message: "You've hit your limit · resets 9am (Asia/Shanghai)",+ } as any,+ id: 'msg-rate-limit',+ }}+ />,+ );++ expect(screen.getByText('guide:claude-code:rate_limit')).toBeInTheDocument();+ });++ it('falls back to the raw error message instead of rendering a blank block', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.undefined' }}+ data={{+ error: {+ body: { detail: 'raw detail' },+ message: 'Raw runtime error',+ } as any,+ id: 'msg-raw',+ }}+ />,+ );++ expect(screen.getByText('Raw runtime error')).toBeInTheDocument();+ expect(screen.getByText(/"detail": "raw detail"/)).toBeInTheDocument();+ });+});diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex b9857e7872b..278edda76e9 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -1,4 +1,5 @@import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobechat/types';@@ -7,11 +8,13 @@ import { type AlertProps } from '@lobehub/ui';import { Block, Highlighter, Skeleton } from '@lobehub/ui';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';import useBusinessErrorAlertConfig from '@/business/client/hooks/useBusinessErrorAlertConfig';import useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorContent';import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRenderBusinessChatErrorMessageExtra';import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';+import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';import { useProviderName } from '@/hooks/useProviderName';import dynamic from '@/libs/next/dynamic';@@ -22,6 +25,26 @@ interface ErrorMessageData {id: string;}+const getRawErrorMessage = (error?: ChatMessageError | null) => {+ if (!error) return;++ if (typeof error.message === 'string' && error.message.trim()) {+ return error.message;+ }++ if (+ error.body &&+ typeof error.body === 'object' &&+ 'message' in error.body &&+ typeof error.body.message === 'string' &&+ error.body.message.trim()+ ) {+ return error.body.message;+ }++ return;+};+const loading = () => (<Blockalign={'center'}@@ -97,17 +120,28 @@ export const useErrorContent = (error: any) => {return useMemo<AlertProps | undefined>(() => {if (!error) return;const messageError = error;+ const rawErrorMessage = getRawErrorMessage(messageError);++ if (!messageError.type) {+ if (!rawErrorMessage) return;++ return {+ message: rawErrorMessage,+ type: 'secondary',+ };+ }// Use business alert config if provided, otherwise fall back to defaultconst alertConfig = businessAlertConfig ?? getErrorAlertConfig(messageError.type);// Use business error type if provided, otherwise use originalconst finalErrorType = businessErrorType ?? messageError.type;+ const translatedMessage = hideMessage+ ? undefined+ : t(`response.${finalErrorType}` as any, { provider: providerName });return {- message: hideMessage- ? undefined- : t(`response.${finalErrorType}` as any, { provider: providerName }),+ message: translatedMessage || rawErrorMessage,...alertConfig,};}, [businessAlertConfig, businessErrorType, error, hideMessage, providerName, t]);@@ -120,14 +154,34 @@ interface ErrorExtraProps {const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) => {const error = data.error;+ const navigate = useNavigate();const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);+ const sessionErrorCode = error?.body?.code;+ const sessionAgentType = error?.body?.agentType;+ const sessionErrorBody = error?.body;+ const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;if (ENABLE_BUSINESS_FEATURES && businessChatErrorMessageExtra)return businessChatErrorMessageExtra;- if (!error?.type) return;+ if (+ (error?.type === AgentRuntimeErrorType.AgentRuntimeError || !error?.type) &&+ !!sessionErrorBody &&+ (sessionErrorCode === HeterogeneousAgentSessionErrorCode.AuthRequired ||+ sessionErrorCode === HeterogeneousAgentSessionErrorCode.CliNotFound ||+ sessionErrorCode === HeterogeneousAgentSessionErrorCode.RateLimit) &&+ (sessionAgentType === 'claude-code' || sessionAgentType === 'codex')+ ) {+ return (+ <HeterogeneousAgentStatusGuide+ agentType={sessionAgentType}+ error={sessionErrorBody}+ onOpenSystemTools={() => navigate('/settings/system-tools')}+ />+ );+ }- switch (error.type) {+ switch (error?.type) {case AgentRuntimeErrorType.OllamaServiceUnavailable: {return <OllamaSetupGuide id={data.id} />;}@@ -147,7 +201,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>}}- if (error.type.toString().includes('Invalid')) {+ if (error?.type?.toString().includes('Invalid')) {return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;}@@ -156,6 +210,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>id={data.id}error={{...alertError,+ ...(rawErrorMessage ? { message: rawErrorMessage } : {}),extra: data.error?.body ? (<HighlighteractionIconSize={'small'}diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 16feccfabd3..04bb009bd7e 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -758,6 +758,100 @@ describe('DataSlice', () => {);});});++ it('should preserve newer local message state when fetched data is stale', async () => {+ const localError = {+ body: { message: 'Codex CLI was not found' },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ } as any;++ vi.mocked(messageService.getMessages).mockResolvedValue([+ {+ id: 'msg-1',+ content: '',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ },+ ]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });++ store.setState({+ dbMessages: [+ {+ id: 'msg-1',+ content: '',+ error: localError,+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 2000,+ },+ ],+ } as any);++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages[0].error).toEqual(localError);+ expect(store.getState().dbMessages[0].updatedAt).toBe(2000);+ });+ });++ it('should accept fetched message state when server data is newer', async () => {+ vi.mocked(messageService.getMessages).mockResolvedValue([+ {+ id: 'msg-1',+ content: '',+ error: {+ body: { message: 'Persisted error' },+ message: 'Persisted error',+ type: 'AgentRuntimeError',+ } as any,+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 3000,+ },+ ]);++ const store = createStore({+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },+ });++ store.setState({+ dbMessages: [+ {+ id: 'msg-1',+ content: '',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 2000,+ },+ ],+ } as any);++ store.getState().useFetchMessages({+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ });++ await waitFor(() => {+ expect(store.getState().dbMessages[0].error).toEqual({+ body: { message: 'Persisted error' },+ message: 'Persisted error',+ type: 'AgentRuntimeError',+ });+ expect(store.getState().dbMessages[0].updatedAt).toBe(3000);+ });+ });});describe('switchMessageBranch', () => {diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex d84386a1c8e..5df1794977e 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -15,6 +15,28 @@ import { dataSelectors } from './selectors';const log = debug('lobe-render:features:Conversation');+const mergeFetchedMessagesWithLocalState = (+ fetchedMessages: UIChatMessage[],+ localMessages: UIChatMessage[],+): UIChatMessage[] => {+ if (localMessages.length === 0 || fetchedMessages.length === 0) return fetchedMessages;++ const localById = new Map(localMessages.map((message) => [message.id, message]));+ let changed = false;++ const mergedMessages = fetchedMessages.map((message) => {+ const localMessage = localById.get(message.id);++ if (!localMessage) return message;+ if (localMessage.updatedAt <= message.updatedAt) return message;++ changed = true;+ return localMessage;+ });++ return changed ? mergedMessages : fetchedMessages;+};+/*** Data Actions*@@ -184,30 +206,31 @@ export const dataSlice: StateCreator<if (!context.topicId) return;const prevDbMessages = get().dbMessages;+ const mergedMessages = mergeFetchedMessagesWithLocalState(data, prevDbMessages);const storeContextKey = messageMapKey(get().context);// Parse messages using conversation-flow- const { flatList } = parse(data);+ const { flatList } = parse(mergedMessages);log('[useFetchMessages] onData | requestContextKey=%s | storeContextKey=%s | prevCount=%d | fetchedCount=%d | displayCount=%d | messageIds=%o',contextKey,storeContextKey,prevDbMessages.length,- data.length,+ mergedMessages.length,flatList.length,- data.slice(0, 5).map((m) => m.id),+ mergedMessages.slice(0, 5).map((m) => m.id),);set({- dbMessages: data,+ dbMessages: mergedMessages,displayMessages: flatList,messagesInit: true,});// Call onMessagesChange callback with the request context (not current context)// This ensures data is stored to the correct topic even if user switched topics- get().onMessagesChange?.(data, context);+ get().onMessagesChange?.(mergedMessages, context);},},);diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsxnew file mode 100644index 00000000000..2735ea540ea--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx@@ -0,0 +1,54 @@+import { isDesktop } from '@lobechat/const';+import { Button, Flexbox } from '@lobehub/ui';+import { ExternalLink, Settings2 } from 'lucide-react';++import { electronSystemService } from '@/services/electron/system';++interface GuideActionsProps {+ docsUrl?: string;+ onOpenSystemTools?: () => void;+ openDocsLabel?: string;+ openSystemToolsLabel?: string;+ showDocs?: boolean;+}++const GuideActions = ({+ docsUrl,+ onOpenSystemTools,+ openDocsLabel,+ openSystemToolsLabel,+ showDocs = false,+}: GuideActionsProps) => {+ const showDocsButton = showDocs && Boolean(docsUrl && openDocsLabel);+ const showSystemToolsButton = Boolean(onOpenSystemTools && openSystemToolsLabel);++ if (!showDocsButton && !showSystemToolsButton) return null;++ return (+ <Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>+ {showSystemToolsButton && (+ <Button icon={<Settings2 size={14} />} size="small" onClick={onOpenSystemTools}>+ {openSystemToolsLabel}+ </Button>+ )}+ {showDocsButton && docsUrl && openDocsLabel && (+ <Button+ icon={<ExternalLink size={14} />}+ size="small"+ type="primary"+ onClick={() => {+ const openLink = isDesktop+ ? electronSystemService.openExternalLink(docsUrl)+ : Promise.resolve(window.open(docsUrl, '_blank', 'noopener,noreferrer'));++ openLink.catch(console.error);+ }}+ >+ {openDocsLabel}+ </Button>+ )}+ </Flexbox>+ );+};++export default GuideActions;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsxnew file mode 100644index 00000000000..6df65a6acff--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsx@@ -0,0 +1,68 @@+import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import type { ReactNode } from 'react';++import type { HeterogeneousAgentStatusGuideVariant } from './types';++interface GuideShellProps {+ actions?: ReactNode;+ children?: ReactNode;+ headerDescription?: ReactNode;+ icon: ReactNode;+ title: string;+ variant: HeterogeneousAgentStatusGuideVariant;+}++const GuideShell = ({+ actions,+ children,+ headerDescription,+ icon,+ title,+ variant,+}: GuideShellProps) => {+ const showHeader = variant !== 'embedded';+ const content = (+ <Flexbox gap={12}>+ {showHeader ? (+ <Flexbox horizontal align="center" gap={12}>+ <Avatar+ avatar={icon}+ background={cssVar.colorFillQuaternary}+ gap={12}+ shape={'square'}+ size={48}+ />+ <Flexbox gap={4}>+ <Text style={{ fontSize: 16, fontWeight: 600 }}>{title}</Text>+ {headerDescription}+ </Flexbox>+ </Flexbox>+ ) : (+ headerDescription+ )}++ {children}+ {actions}+ </Flexbox>+ );++ if (variant !== 'inline') return content;++ return (+ <Block+ gap={16}+ padding={16}+ variant={'outlined'}+ style={{+ background: cssVar.colorBgElevated,+ overflow: 'hidden',+ width: '100%',+ }}+ >+ {content}+ </Block>+ );+};++export default GuideShell;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsxnew file mode 100644index 00000000000..e2f77407fae--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx@@ -0,0 +1,50 @@+import {+ CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ CODEX_CLI_INSTALL_COMMANDS,+ CODEX_CLI_INSTALL_DOCS_URL,+} from '@lobechat/electron-client-ipc';+import { ClaudeCode, Codex } from '@lobehub/icons';++import {+ type HeterogeneousAgentGuideConfig,+ SUPPORTED_HETEROGENEOUS_AGENT_TYPES,+ type SupportedHeterogeneousAgentType,+} from './types';++export const HETEROGENEOUS_AGENT_GUIDE_CONFIG = {+ 'claude-code': {+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ icon: ClaudeCode,+ installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,+ signInCommand: 'claude',+ title: 'Claude Code',+ translationPrefix: 'claudeCodeInstallGuide',+ },+ 'codex': {+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,+ icon: Codex,+ installCommands: CODEX_CLI_INSTALL_COMMANDS,+ signInCommand: 'codex',+ title: 'Codex',+ translationPrefix: 'codexInstallGuide',+ },+} as const satisfies Record<SupportedHeterogeneousAgentType, HeterogeneousAgentGuideConfig>;++export const isSupportedHeterogeneousAgentType = (+ value?: string,+): value is SupportedHeterogeneousAgentType =>+ !!value && SUPPORTED_HETEROGENEOUS_AGENT_TYPES.includes(value as SupportedHeterogeneousAgentType);++export const resolveHeterogeneousAgentGuideConfig = (options: {+ agentType?: string;+ errorAgentType?: string;+}) => {+ const resolvedAgentType = isSupportedHeterogeneousAgentType(options.errorAgentType)+ ? options.errorAgentType+ : isSupportedHeterogeneousAgentType(options.agentType)+ ? options.agentType+ : 'codex';++ return HETEROGENEOUS_AGENT_GUIDE_CONFIG[resolvedAgentType];+};diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsxnew file mode 100644index 00000000000..308bef7819f--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx@@ -0,0 +1,317 @@+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { describe, expect, it, vi } from 'vitest';++import HeterogeneousAgentStatusGuide from './index';++vi.mock('@lobechat/const', () => ({+ isDesktop: false,+}));++vi.mock('@lobehub/icons', () => ({+ ClaudeCode: () => <span>Claude Code Icon</span>,+ Codex: () => <span>Codex Icon</span>,+}));++vi.mock('@lobehub/ui', () => ({+ Avatar: ({ avatar }: { avatar?: ReactNode }) => <div>{avatar}</div>,+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Button: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (+ <button type="button" onClick={onClick}>+ {children}+ </button>+ ),+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Highlighter: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (+ <pre style={style}>{children}</pre>+ ),+ Snippet: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (+ <pre style={style}>{children}</pre>+ ),+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+}));++vi.mock('antd-style', () => ({+ cssVar: {+ colorBgElevated: 'transparent',+ colorFillQuaternary: 'transparent',+ },+}));++vi.mock('lucide-react', () => ({+ ExternalLink: () => <span>ExternalLink Icon</span>,+ Settings2: () => <span>Settings Icon</span>,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: {+ language: 'en-US',+ resolvedLanguage: 'en-US',+ },+ t: (+ key: string,+ options?: { count?: number; duration?: string; message?: string; name?: string },+ ) => {+ if (key === 'cliRateLimitGuide.relative.day') {+ return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'day' : 'days'}`;+ }++ if (key === 'cliRateLimitGuide.relative.hour') {+ return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'hour' : 'hours'}`;+ }++ if (key === 'cliRateLimitGuide.relative.minute') {+ return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'minute' : 'minutes'}`;+ }++ if (key === 'cliRateLimitGuide.resetInApprox') {+ return `Resets in about ${options?.duration ?? ''}`;+ }++ return (+ (+ {+ '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.',+ 'cliAuthGuide.desc': `${options?.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',+ 'cliAuthGuide.title': `Sign in to ${options?.name ?? ''}`,+ 'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',+ 'cliRateLimitGuide.afterReset':+ 'Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.',+ 'cliRateLimitGuide.desc': `${options?.name ?? ''} has reached its current usage limit and cannot continue this run right now.`,+ 'cliRateLimitGuide.limitType': 'Limit window',+ 'cliRateLimitGuide.limitTypes.weekCycle': 'Week cycle',+ 'cliRateLimitGuide.relative.soon': 'Resets soon',+ 'cliRateLimitGuide.resetAt': 'Resets at',+ 'cliRateLimitGuide.title': `${options?.name ?? ''} usage limit reached`,+ 'claudeCodeInstallGuide.actions.openDocs': 'Open Install Guide',+ 'claudeCodeInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'claudeCodeInstallGuide.afterInstall':+ 'After installing, run Claude Code once to sign in, then retry your message.',+ 'claudeCodeInstallGuide.desc':+ 'Claude Code needs the Claude Code CLI to run locally. Install it first.',+ 'claudeCodeInstallGuide.installWithBrew': 'Homebrew',+ 'claudeCodeInstallGuide.installWithNpm': 'Recommended install',+ 'claudeCodeInstallGuide.reason': `LobeHub could not start Claude Code: ${options?.message ?? ''}`,+ 'claudeCodeInstallGuide.title': 'Install Claude Code CLI',+ 'codexInstallGuide.actions.openDocs': 'Open Install Guide',+ 'codexInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'codexInstallGuide.afterInstall':+ 'After installing, run Codex once to sign in, then retry your message.',+ 'codexInstallGuide.desc':+ 'Codex Agent needs the Codex CLI to run locally. Install it first.',+ 'codexInstallGuide.installWithBrew': 'Homebrew',+ 'codexInstallGuide.installWithNpm': 'Recommended install',+ 'codexInstallGuide.reason': `LobeHub could not start Codex: ${options?.message ?? ''}`,+ 'codexInstallGuide.title': 'Install Codex CLI',+ } as Record<string, string>+ )[key] || key+ );+ },+ }),+}));++vi.mock('@/services/electron/system', () => ({+ electronSystemService: {+ openExternalLink: vi.fn(),+ },+}));++describe('HeterogeneousAgentStatusGuide', () => {+ it('hides the duplicated reason for the known cli_not_found state', () => {+ render(+ <HeterogeneousAgentStatusGuide+ error={{+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ message: 'Codex CLI was not found',+ }}+ />,+ );++ expect(screen.getByText('Install Codex CLI')).toBeInTheDocument();+ expect(screen.queryByText(/LobeHub could not start Codex:/)).not.toBeInTheDocument();+ });++ it('keeps the detailed reason for unexpected errors', () => {+ render(+ <HeterogeneousAgentStatusGuide+ error={{+ code: 'spawn_failed',+ message: 'Permission denied',+ }}+ />,+ );++ expect(+ screen.getByText('LobeHub could not start Codex: Permission denied'),+ ).toBeInTheDocument();+ });++ it('uses a headerless layout in embedded mode', () => {+ render(<HeterogeneousAgentStatusGuide variant={'embedded'} />);++ expect(screen.queryByText('Install Codex CLI')).not.toBeInTheDocument();+ expect(+ screen.getByText('Codex Agent needs the Codex CLI to run locally. Install it first.'),+ ).toBeInTheDocument();+ });++ it('renders Claude Code install guidance for the Claude CLI flow', () => {+ render(+ <HeterogeneousAgentStatusGuide+ agentType={'claude-code'}+ error={{+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ message: 'Claude Code CLI was not found',+ }}+ />,+ );++ expect(screen.getByText('Install Claude Code CLI')).toBeInTheDocument();+ expect(+ screen.getByText('Claude Code needs the Claude Code CLI to run locally. Install it first.'),+ ).toBeInTheDocument();+ expect(screen.getByText('curl -fsSL https://claude.ai/install.sh | bash')).toBeInTheDocument();+ expect(screen.queryByText(/LobeHub could not start Claude Code:/)).not.toBeInTheDocument();+ });++ it('renders sign-in guidance for auth-required errors', () => {+ render(+ <HeterogeneousAgentStatusGuide+ agentType={'claude-code'}+ error={{+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ message: 'Failed to authenticate.\nAPI Error: 401',+ }}+ />,+ );++ expect(screen.getByText('Sign in to Claude Code')).toBeInTheDocument();+ expect(+ screen.getByText(+ 'Claude Code could not continue because its sign-in session expired or the credentials are invalid.',+ ),+ ).toBeInTheDocument();+ expect(screen.getByText('Run this in Terminal')).toBeInTheDocument();+ expect(screen.getByText('claude')).toBeInTheDocument();+ expect(screen.getByText('Error details')).toBeInTheDocument();+ const errorDetails = screen.getByText(+ (_, element) => element?.textContent === 'Failed to authenticate.\nAPI Error: 401',+ );+ expect(errorDetails).toBeInTheDocument();+ expect(errorDetails).toHaveStyle({+ maxHeight: '200px',+ overflow: 'auto',+ });+ });++ it('renders rate-limit guidance with structured metadata', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));++ try {+ render(+ <HeterogeneousAgentStatusGuide+ agentType={'claude-code'}+ error={{+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.RateLimit,+ message: "You've hit your limit · resets 9am (Asia/Shanghai)",+ rateLimitInfo: {+ rateLimitType: 'seven_day',+ resetsAt: 1_776_992_400,+ },+ }}+ />,+ );++ expect(screen.getByText('Claude Code usage limit reached')).toBeInTheDocument();+ expect(screen.getByText(/Resets in about 19 hours 33 minutes/)).toBeInTheDocument();+ expect(+ screen.getByText(+ 'Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.',+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(+ 'Claude Code has reached its current usage limit and cannot continue this run right now.',+ ),+ ).not.toBeInTheDocument();+ expect(screen.getByText('Resets at')).toBeInTheDocument();+ expect(screen.getByText('Limit window')).toBeInTheDocument();+ expect(screen.getByText('Week cycle')).toBeInTheDocument();+ expect(screen.getByText(/Fri 9:00 AM \(Asia\/Shanghai\)/)).toBeInTheDocument();+ expect(screen.getByText(/Asia\/Shanghai/)).toBeInTheDocument();+ expect(screen.queryByText('Open Install Guide')).not.toBeInTheDocument();+ expect(screen.queryByText('Recommended install')).not.toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });++ it('formats reset time with the active i18n locale instead of the system locale', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));++ const dateTimeFormatSpy = vi.spyOn(Intl, 'DateTimeFormat').mockImplementation(((+ locale?: string | string[],+ options?: Intl.DateTimeFormatOptions,+ ) => {+ const resolvedLocale = Array.isArray(locale) ? locale[0] : locale;++ return {+ format: () => {+ if (options?.weekday === 'short') {+ return resolvedLocale === 'en-US' ? 'Fri 9:00 AM' : '周五 09:00';+ }++ return resolvedLocale === 'en-US' ? 'Apr 24, 2026, 9:00 AM' : '2026年4月24日 09:00';+ },+ resolvedOptions: () => ({+ calendar: 'gregory',+ locale: resolvedLocale || 'zh-CN',+ numberingSystem: 'latn',+ timeZone: 'Asia/Shanghai',+ }),+ } as Intl.DateTimeFormat;+ }) as typeof Intl.DateTimeFormat);++ try {+ render(+ <HeterogeneousAgentStatusGuide+ agentType={'claude-code'}+ error={{+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.RateLimit,+ message: "You've hit your limit · resets 9am (Asia/Shanghai)",+ rateLimitInfo: {+ rateLimitType: 'seven_day',+ resetsAt: 1_776_992_400,+ },+ }}+ />,+ );++ expect(screen.getByText(/Fri 9:00 AM \(Asia\/Shanghai\)/)).toBeInTheDocument();+ expect(dateTimeFormatSpy).toHaveBeenCalledWith(+ 'en-US',+ expect.objectContaining({+ hour: 'numeric',+ minute: '2-digit',+ weekday: 'short',+ }),+ );+ } finally {+ dateTimeFormatSpy.mockRestore();+ vi.useRealTimers();+ }+ });+});diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsxnew file mode 100644index 00000000000..1eac745a924--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx@@ -0,0 +1,43 @@+'use client';++import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { memo } from 'react';++import { resolveHeterogeneousAgentGuideConfig } from './config';+import AuthRequiredState from './states/AuthRequiredState';+import CliInstallState from './states/CliInstallState';+import RateLimitState from './states/RateLimitState';+import type { HeterogeneousAgentStatusGuideProps } from './types';++const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(+ ({ agentType = 'codex', error, onOpenSystemTools, variant = 'inline' }) => {+ const config = resolveHeterogeneousAgentGuideConfig({+ agentType,+ errorAgentType: error?.agentType,+ });+ const stateProps = {+ config,+ error,+ onOpenSystemTools,+ variant,+ };++ switch (error?.code) {+ case HeterogeneousAgentSessionErrorCode.AuthRequired: {+ return <AuthRequiredState {...stateProps} />;+ }++ case HeterogeneousAgentSessionErrorCode.RateLimit: {+ return <RateLimitState {...stateProps} />;+ }++ default: {+ return <CliInstallState {...stateProps} />;+ }+ }+ },+);++HeterogeneousAgentStatusGuide.displayName = 'HeterogeneousAgentStatusGuide';++export default HeterogeneousAgentStatusGuide;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsxnew file mode 100644index 00000000000..54bdeeb947f--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsx@@ -0,0 +1,71 @@+import { Flexbox, Highlighter, Snippet, Text } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import GuideActions from '../GuideActions';+import GuideShell from '../GuideShell';+import type { HeterogeneousAgentGuideStateProps } from '../types';++const AuthRequiredState = ({+ config,+ error,+ onOpenSystemTools,+ variant,+}: HeterogeneousAgentGuideStateProps) => {+ const { t } = useTranslation('chat');+ const rawErrorDetails = error?.stderr || error?.message;+ const docsUrl = error?.docsUrl || config.docsUrl;++ return (+ <GuideShell+ headerDescription={+ <Text type="secondary">{t('cliAuthGuide.desc', { name: config.title })}</Text>+ }+ icon={<config.icon size={24} />}+ title={t('cliAuthGuide.title', { name: config.title })}+ variant={variant}+ actions={+ <GuideActions+ showDocs+ docsUrl={docsUrl}+ openDocsLabel={t('cliAuthGuide.actions.openDocs')}+ openSystemToolsLabel={t('cliAuthGuide.actions.openSystemTools')}+ onOpenSystemTools={onOpenSystemTools}+ />+ }+ >+ <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')}+ </Text>++ {rawErrorDetails && (+ <Flexbox gap={6}>+ <Text strong style={{ fontSize: 12 }}>+ {t('cliAuthGuide.errorDetails')}+ </Text>+ <Highlighter+ wrap+ actionIconSize={'small'}+ language={'log'}+ padding={12}+ variant={'outlined'}+ style={{+ maxHeight: 200,+ overflow: 'auto',+ }}+ >+ {rawErrorDetails}+ </Highlighter>+ </Flexbox>+ )}+ </GuideShell>+ );+};++export default AuthRequiredState;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/CliInstallState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/CliInstallState.tsxnew file mode 100644index 00000000000..f387e09c563--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/CliInstallState.tsx@@ -0,0 +1,77 @@+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { Flexbox, Snippet, Text } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import GuideActions from '../GuideActions';+import GuideShell from '../GuideShell';+import type { HeterogeneousAgentGuideStateProps } from '../types';++const CliInstallState = ({+ config,+ error,+ onOpenSystemTools,+ variant,+}: HeterogeneousAgentGuideStateProps) => {+ const { t } = useTranslation('chat');+ const translationPrefix = config.translationPrefix;+ const docsUrl = error?.docsUrl || config.docsUrl;+ const installCommands = error?.installCommands?.length+ ? error.installCommands+ : config.installCommands;+ const [recommendedCommand, alternativeCommand] = installCommands;+ const showErrorReason =+ Boolean(error?.message) && error?.code !== HeterogeneousAgentSessionErrorCode.CliNotFound;++ // `translationPrefix` is dynamic at runtime, so use the string-key overload+ // with `defaultValue` to satisfy the i18n key typing.+ const tKey = (suffix: string, options?: Record<string, unknown>) =>+ t(`${translationPrefix}.${suffix}`, { defaultValue: '', ...options });++ return (+ <GuideShell+ headerDescription={<Text type="secondary">{tKey('desc')}</Text>}+ icon={<config.icon size={24} />}+ title={tKey('title')}+ variant={variant}+ actions={+ <GuideActions+ showDocs+ docsUrl={docsUrl}+ openDocsLabel={tKey('actions.openDocs')}+ openSystemToolsLabel={tKey('actions.openSystemTools')}+ onOpenSystemTools={onOpenSystemTools}+ />+ }+ >+ {showErrorReason && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {tKey('reason', { message: error?.message })}+ </Text>+ )}++ {recommendedCommand && (+ <Flexbox gap={6}>+ <Text strong style={{ fontSize: 12 }}>+ {tKey('installWithNpm')}+ </Text>+ <Snippet language={'bash'}>{recommendedCommand}</Snippet>+ </Flexbox>+ )}++ {alternativeCommand && (+ <Flexbox gap={6}>+ <Text strong style={{ fontSize: 12 }}>+ {tKey('installWithBrew')}+ </Text>+ <Snippet language={'bash'}>{alternativeCommand}</Snippet>+ </Flexbox>+ )}++ <Text style={{ fontSize: 12 }} type="secondary">+ {tKey('afterInstall')}+ </Text>+ </GuideShell>+ );+};++export default CliInstallState;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsxnew file mode 100644index 00000000000..18fdb066044--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx@@ -0,0 +1,134 @@+import { Flexbox, Text } from '@lobehub/ui';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import GuideActions from '../GuideActions';+import GuideShell from '../GuideShell';+import type { HeterogeneousAgentGuideStateProps } from '../types';++const extractTimezoneLabel = (value?: string) => {+ if (!value) return;++ const match = value.match(/\(([^()]+)\)\s*$/);+ return match?.[1];+};++const RateLimitState = ({+ config,+ error,+ onOpenSystemTools,+ variant,+}: HeterogeneousAgentGuideStateProps) => {+ const { t, i18n } = useTranslation('chat');+ const rawErrorDetails = error?.stderr || error?.message;+ const dateLocale = i18n.resolvedLanguage || i18n.language || undefined;+ const timezoneLabel = useMemo(+ () => extractTimezoneLabel(rawErrorDetails) || Intl.DateTimeFormat().resolvedOptions().timeZone,+ [rawErrorDetails],+ );+ const formattedResetAt = useMemo(() => {+ const resetsAt = error?.rateLimitInfo?.resetsAt;+ if (!resetsAt) return;++ try {+ return new Intl.DateTimeFormat(dateLocale, {+ hour: 'numeric',+ minute: '2-digit',+ ...(timezoneLabel ? { timeZone: timezoneLabel } : {}),+ weekday: 'short',+ }).format(new Date(resetsAt * 1000));+ } catch {+ try {+ return new Intl.DateTimeFormat(dateLocale, {+ dateStyle: 'medium',+ timeStyle: 'short',+ }).format(new Date(resetsAt * 1000));+ } catch {+ return;+ }+ }+ }, [dateLocale, error?.rateLimitInfo?.resetsAt, timezoneLabel]);+ const rateLimitTypeLabel = useMemo(() => {+ const rateLimitType = error?.rateLimitInfo?.rateLimitType;+ if (!rateLimitType) return;++ if (rateLimitType === 'seven_day') {+ return t('cliRateLimitGuide.limitTypes.weekCycle');+ }++ return rateLimitType.replaceAll('_', ' ');+ }, [error?.rateLimitInfo?.rateLimitType, t]);+ const relativeResetText = useMemo(() => {+ const resetsAt = error?.rateLimitInfo?.resetsAt;+ if (!resetsAt) return;++ const now = Date.now();+ const diffMs = Math.max(0, resetsAt * 1000 - now);+ const totalMinutes = Math.floor(diffMs / 60_000);++ if (totalMinutes <= 0) return t('cliRateLimitGuide.relative.soon');++ const days = Math.floor(totalMinutes / (24 * 60));+ const hours = Math.floor((totalMinutes % (24 * 60)) / 60);+ const minutes = totalMinutes % 60;+ const parts: string[] = [];++ if (days > 0) parts.push(t('cliRateLimitGuide.relative.day', { count: days }));+ if (hours > 0) parts.push(t('cliRateLimitGuide.relative.hour', { count: hours }));+ if (minutes > 0 && parts.length < 2) {+ parts.push(t('cliRateLimitGuide.relative.minute', { count: minutes }));+ }++ return parts.length > 0+ ? t('cliRateLimitGuide.resetInApprox', { duration: parts.slice(0, 2).join(' ') })+ : t('cliRateLimitGuide.relative.soon');+ }, [error?.rateLimitInfo?.resetsAt, t]);++ return (+ <GuideShell+ headerDescription={<Text type="secondary">{t('cliRateLimitGuide.afterReset')}</Text>}+ icon={<config.icon size={24} />}+ title={t('cliRateLimitGuide.title', { name: config.title })}+ variant={variant}+ actions={+ <GuideActions+ openSystemToolsLabel={t('cliRateLimitGuide.actions.openSystemTools')}+ onOpenSystemTools={onOpenSystemTools}+ />+ }+ >+ <Flexbox gap={8}>+ {formattedResetAt && (+ <Flexbox horizontal gap={8} style={{ alignItems: 'baseline' }}>+ <Text strong style={{ fontSize: 12 }}>+ {t('cliRateLimitGuide.resetAt')}+ </Text>+ <Flexbox+ horizontal+ gap={8}+ style={{ alignItems: 'baseline', flexWrap: 'nowrap', whiteSpace: 'nowrap' }}+ >+ <Text>{`${formattedResetAt}${timezoneLabel ? ` (${timezoneLabel})` : ''}`}</Text>+ {relativeResetText && (+ <Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type="secondary">+ {relativeResetText}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ )}++ {rateLimitTypeLabel && (+ <Flexbox horizontal align="center" gap={8}>+ <Text strong style={{ fontSize: 12 }}>+ {t('cliRateLimitGuide.limitType')}+ </Text>+ <Text>{rateLimitTypeLabel}</Text>+ </Flexbox>+ )}+ </Flexbox>+ </GuideShell>+ );+};++export default RateLimitState;diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsnew file mode 100644index 00000000000..91f28bf7e59--- /dev/null+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -0,0 +1,31 @@+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import type { ComponentType } from 'react';++export type HeterogeneousAgentStatusGuideVariant = 'compact' | 'embedded' | 'inline';++export interface HeterogeneousAgentStatusGuideProps {+ agentType?: string;+ error?: HeterogeneousAgentSessionError | null;+ onOpenSystemTools?: () => void;+ variant?: HeterogeneousAgentStatusGuideVariant;+}++export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = ['claude-code', 'codex'] as const;++export type SupportedHeterogeneousAgentType = (typeof SUPPORTED_HETEROGENEOUS_AGENT_TYPES)[number];++export interface HeterogeneousAgentGuideConfig {+ docsUrl: string;+ icon: ComponentType<{ size?: number }>;+ installCommands: readonly string[];+ signInCommand: string;+ title: string;+ translationPrefix: string;+}++export interface HeterogeneousAgentGuideStateProps {+ config: HeterogeneousAgentGuideConfig;+ error?: HeterogeneousAgentSessionError | null;+ onOpenSystemTools?: () => void;+ variant: HeterogeneousAgentStatusGuideVariant;+}diff --git a/src/locales/create.ts b/src/locales/create.tsindex fef5d63070e..8c8f52fb59a 100644--- a/src/locales/create.ts+++ b/src/locales/create.ts@@ -4,23 +4,36 @@ import resourcesToBackend from 'i18next-resources-to-backend';import { initReactI18next } from 'react-i18next';import { isRtlLang } from 'rtl-detect';-// Sync load default language (en-US) from JSON to avoid Suspense on first render.-// locales/default/*.ts is for type inference only, not used as runtime values.import chat from '@/../locales/en-US/chat.json';import common from '@/../locales/en-US/common.json';import error from '@/../locales/en-US/error.json';import { DEFAULT_LANG } from '@/const/locale';import { getDebugConfig } from '@/envs/debug';+// Sync load bundled fallback resources without Suspense on first render.+// Use src/locales/default/*.ts as the runtime fallback source, then overlay+// locales/en-US/*.json so dev-preview JSON can still customize English copy+// without dropping newly added default keys.+import defaultChat from '@/locales/default/chat';+import defaultCommon from '@/locales/default/common';+import defaultError from '@/locales/default/error';import { normalizeLocale } from '@/locales/resources';import { isOnServerSide } from '@/utils/env';import { unwrapESMModule } from '@/utils/esm/unwrapESMModule';import { loadI18nNamespaceModule } from '../utils/i18n/loadI18nNamespaceModule';+const mergeNamespace = (+ fallbackResources: Record<string, string>,+ localeResources: Record<string, string>,+) => ({+ ...fallbackResources,+ ...localeResources,+});+const createBundledResources = () => ({- chat: { ...chat },- common: { ...common },- error: { ...error },+ chat: mergeNamespace(defaultChat, chat),+ common: mergeNamespace(defaultCommon, common),+ error: mergeNamespace(defaultError, error),});const defaultResources = createBundledResources();diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 0e882a6da35..bd29154e7e2 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -152,6 +152,8 @@ export default {'Claude Code runs locally with full read/write access to the working directory. Switching permission modes is not available yet.','heteroAgent.resumeReset.cwdChanged':'Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.',+ 'heteroAgent.resumeReset.resumeFailed':+ 'The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.','heteroAgent.switchCwd.cancel': 'Cancel','heteroAgent.switchCwd.content':'Claude Code sessions are pinned to a working directory. Switching will start a new session for this topic — chat messages stay, but the previous session context cannot be resumed.',@@ -260,8 +262,57 @@ export default {'createModal.groupTitle': 'What should your group do?','createModal.placeholder': 'Describe what your agent should do...','createModal.title': 'What should your agent do?',+ 'claudeCodeInstallGuide.actions.openDocs': 'Open Install Guide',+ 'claudeCodeInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'claudeCodeInstallGuide.afterInstall':+ 'After installing, run Claude Code once to sign in, then retry your message or click Re-detect in System Tools.',+ 'claudeCodeInstallGuide.desc':+ 'Claude Code needs the Claude Code CLI to run locally. Install it and make sure the `claude` command is available in your PATH.',+ 'claudeCodeInstallGuide.installWithBrew': 'Homebrew',+ 'claudeCodeInstallGuide.installWithNpm': 'Recommended install',+ 'claudeCodeInstallGuide.menuNotification.title': 'Claude Code CLI not found',+ 'claudeCodeInstallGuide.reason': 'LobeHub could not start Claude Code: {{message}}',+ 'claudeCodeInstallGuide.title': 'Install Claude Code CLI',+ '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.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',+ 'cliAuthGuide.title': 'Sign in to {{name}}',+ 'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',+ 'cliRateLimitGuide.afterReset':+ 'Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.',+ 'cliRateLimitGuide.desc':+ '{{name}} has reached its current usage limit and cannot continue this run right now.',+ 'cliRateLimitGuide.limitType': 'Limit window',+ 'cliRateLimitGuide.limitTypes.weekCycle': 'Week cycle',+ 'cliRateLimitGuide.relative.day_one': '{{count}} day',+ 'cliRateLimitGuide.relative.day_other': '{{count}} days',+ 'cliRateLimitGuide.relative.hour_one': '{{count}} hour',+ 'cliRateLimitGuide.relative.hour_other': '{{count}} hours',+ 'cliRateLimitGuide.relative.minute_one': '{{count}} minute',+ 'cliRateLimitGuide.relative.minute_other': '{{count}} minutes',+ 'cliRateLimitGuide.relative.soon': 'Resets soon',+ 'cliRateLimitGuide.resetAt': 'Resets at',+ 'cliRateLimitGuide.resetInApprox': 'Resets in about {{duration}}',+ 'cliRateLimitGuide.title': '{{name}} usage limit reached',+ 'codexInstallGuide.actions.openDocs': 'Open Install Guide',+ 'codexInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'codexInstallGuide.afterInstall':+ 'After installing, run Codex once to sign in, then retry your message or click Re-detect in System Tools.',+ 'codexInstallGuide.desc':+ 'Codex Agent needs the Codex CLI to run locally. Install it and make sure the codex command is available in your PATH.',+ 'codexInstallGuide.installWithBrew': 'Homebrew (macOS)',+ 'codexInstallGuide.installWithNpm': 'Recommended install',+ 'codexInstallGuide.menuNotification.title': 'Codex CLI not found',+ 'codexInstallGuide.reason': 'LobeHub could not start Codex: {{message}}',+ 'codexInstallGuide.title': 'Install Codex CLI','newAgent': 'Create Agent','newClaudeCodeAgent': 'Add Claude Code',+ 'newCodexAgent': 'Add Codex','newGroupChat': 'Create Group','newPage': 'Create Page','noAgentsYet': 'This group has no members yet. Click the + button to invite agents.',diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex 4226e504899..b08b0dcc225 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -207,12 +207,18 @@ export default {'analytics.telemetry.title': 'Send Anonymous Usage Data','analytics.title': 'Analytics',- // Claude Code CLI status (shown on agent profile page in CC integration mode)- 'ccStatus.account.label': 'Account',- 'ccStatus.detecting': 'Detecting Claude Code CLI...',- 'ccStatus.redetect': 'Re-detect',- 'ccStatus.title': 'Claude Code CLI',- 'ccStatus.unavailable': 'Claude Code CLI not found. Please install or configure it.',+ // Heterogeneous agent CLI status (shown on agent profile page in integration mode)+ 'heterogeneousStatus.account.label': 'Account',+ 'heterogeneousStatus.auth.api': 'API',+ 'heterogeneousStatus.auth.label': 'Auth Method',+ 'heterogeneousStatus.auth.subscription': 'Subscription',+ 'heterogeneousStatus.command.edit': 'Edit command',+ 'heterogeneousStatus.command.label': 'Launch Command',+ 'heterogeneousStatus.command.placeholder': 'Command name or absolute path',+ 'heterogeneousStatus.detecting': 'Detecting {{name}} CLI...',+ 'heterogeneousStatus.plan.label': 'Plan',+ 'heterogeneousStatus.redetect': 'Re-detect',+ 'heterogeneousStatus.unavailable': '{{name}} CLI not found. Please install or configure it.','checking': 'Checking...',// Credentials Managementdiff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/CCStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/CCStatusCard.tsxdeleted file mode 100644index 0351e0b873a..00000000000--- a/src/routes/(main)/agent/profile/features/ProfileEditor/CCStatusCard.tsx+++ /dev/null@@ -1,152 +0,0 @@-'use client';--import { isDesktop } from '@lobechat/const';-import { type ClaudeAuthStatus, type ToolStatus } from '@lobechat/electron-client-ipc';-import { ActionIcon, CopyButton, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';-import { createStyles } from 'antd-style';-import { CheckCircle2, Loader2Icon, RefreshCw, XCircle } from 'lucide-react';-import { memo, useCallback, useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { toolDetectorService } from '@/services/electron/toolDetector';--const useStyles = createStyles(({ css, token }) => ({- card: css`- padding-block: 8px;- padding-inline: 12px;- border: 1px solid ${token.colorBorderSecondary};- border-radius: ${token.borderRadiusLG}px;-- background: ${token.colorFillQuaternary};- `,- label: css`- min-width: 72px;- font-size: 12px;- color: ${token.colorTextTertiary};- `,- path: css`- font-family: ${token.fontFamilyCode};- font-size: 12px;- color: ${token.colorTextTertiary};- `,-}));--const CCStatusCard = memo(() => {- const { t } = useTranslation('setting');- const { styles } = useStyles();- const [status, setStatus] = useState<ToolStatus | undefined>();- const [auth, setAuth] = useState<ClaudeAuthStatus | null>(null);- const [detecting, setDetecting] = useState(true);-- // Fetched independently of `detectTool`: an auth-fetch failure must not- // flip the CLI status card to unavailable.- const fetchAuth = useCallback(async () => {- try {- const result = await toolDetectorService.getClaudeAuthStatus();- setAuth(result);- } catch (error) {- console.warn('[CCStatusCard] Failed to get claude auth status:', error);- setAuth(null);- }- }, []);-- const detect = useCallback(async () => {- if (!isDesktop) return;- setDetecting(true);- try {- const result = await toolDetectorService.detectTool('claude', true);- setStatus(result);- } catch (error) {- console.error('[CCStatusCard] Failed to detect claude CLI:', error);- setStatus({ available: false, error: (error as Error).message });- } finally {- setDetecting(false);- }- void fetchAuth();- }, [fetchAuth]);-- useEffect(() => {- void detect();- }, [detect]);-- const renderBody = () => {- if (detecting) {- return (- <Flexbox horizontal align="center" gap={8}>- <Icon spin icon={Loader2Icon} size={16} style={{ opacity: 0.6 }} />- <Text type="secondary">{t('ccStatus.detecting')}</Text>- </Flexbox>- );- }-- if (!status || !status.available) {- return (- <Flexbox horizontal align="center" gap={8}>- <Icon color="var(--ant-color-error)" icon={XCircle} size={16} />- <Text type="secondary">{t('ccStatus.unavailable')}</Text>- </Flexbox>- );- }-- return (- <Flexbox horizontal align="center" gap={8} style={{ flex: 1, minWidth: 0 }}>- <Icon color="var(--ant-color-success)" icon={CheckCircle2} size={16} />- {status.version && <Tag color="processing">{status.version}</Tag>}- {status.path && (- <Tooltip title={status.path}>- <Flexbox- horizontal- align="center"- gap={4}- style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}- >- <Text ellipsis className={styles.path}>- {status.path}- </Text>- <CopyButton content={status.path} size="small" />- </Flexbox>- </Tooltip>- )}- </Flexbox>- );- };-- const renderAuth = () => {- if (detecting || !status?.available || !auth?.loggedIn) return null;-- return (- <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>- <Text className={styles.label}>{t('ccStatus.account.label')}</Text>- {auth.email && <Text ellipsis>{auth.email}</Text>}- {auth.subscriptionType && (- <Tag color="gold" style={{ marginInlineEnd: 0 }}>- {auth.subscriptionType.toUpperCase()}- </Tag>- )}- </Flexbox>- );- };-- return (- <Flexbox className={styles.card} gap={8} style={{ marginBottom: 12 }}>- <Flexbox horizontal align="center" gap={8} justify="space-between">- <Text strong>{t('ccStatus.title')}</Text>- <Tooltip title={t('ccStatus.redetect')}>- <ActionIcon- disabled={detecting}- icon={RefreshCw}- loading={detecting}- size="small"- onClick={detect}- />- </Tooltip>- </Flexbox>- {renderBody()}- {renderAuth()}- </Flexbox>- );-});--CCStatusCard.displayName = 'CCStatusCard';--export default CCStatusCard;diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsxnew file mode 100644index 00000000000..7da735b8ab5--- /dev/null+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx@@ -0,0 +1,308 @@+import type { HeterogeneousProviderConfig } from '@lobechat/types';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++import HeterogeneousAgentStatusCard from './HeterogeneousAgentStatusCard';++const { detectHeterogeneousAgentCommand, getClaudeAuthStatus } = vi.hoisted(() => ({+ detectHeterogeneousAgentCommand: vi.fn(),+ getClaudeAuthStatus: vi.fn(),+}));++vi.mock('@lobechat/const', () => ({+ isDesktop: true,+}));++vi.mock('@lobechat/heterogeneous-agents/client', () => ({+ getHeterogeneousAgentClientConfig: (type: string) =>+ type === 'claude-code'+ ? {+ command: 'claude',+ icon: () => <span>Claude Code Icon</span>,+ title: 'Claude Code',+ }+ : {+ command: 'codex',+ icon: () => <span>Codex Icon</span>,+ title: 'Codex',+ },+}));++vi.mock('@lobehub/ui', () => ({+ ActionIcon: ({+ 'aria-label': ariaLabel,+ className,+ onClick,+ }: {+ 'aria-label'?: string;+ 'className'?: string;+ 'onClick'?: () => void;+ }) => (+ <button aria-label={ariaLabel} className={className} type="button" onClick={onClick}>+ Refresh+ </button>+ ),+ CopyButton: () => <button type="button">Copy</button>,+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Icon: () => <span>Icon</span>,+ Input: ({+ onBlur,+ onChange,+ onKeyDown,+ placeholder,+ ref,+ value,+ }: {+ onBlur?: () => void;+ onChange?: (event: { target: { value: string } }) => void;+ onKeyDown?: (event: { key: string; preventDefault: () => void }) => void;+ placeholder?: string;+ ref?: React.Ref<HTMLInputElement>;+ value?: string;+ }) => (+ <input+ placeholder={placeholder}+ ref={ref}+ value={value}+ onBlur={onBlur}+ onChange={(event) => {+ onChange?.({ target: { value: event.target.value } });+ }}+ onKeyDown={(event) => {+ onKeyDown?.({ key: event.key, preventDefault: () => event.preventDefault() });+ }}+ />+ ),+ Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+ Tooltip: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+}));++vi.mock('antd-style', () => ({+ createStyles: () => () => ({+ styles: {+ card: 'card',+ label: 'label',+ path: 'path',+ },+ }),+}));++vi.mock('lucide-react', () => ({+ CheckCircle2: () => null,+ Loader2Icon: () => null,+ PencilLine: () => null,+ RefreshCw: () => null,+ XCircle: () => null,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { name?: string }) =>+ (+ ({+ 'heterogeneousStatus.account.label': 'Account',+ 'heterogeneousStatus.auth.api': 'API',+ 'heterogeneousStatus.auth.label': 'Auth Method',+ 'heterogeneousStatus.auth.subscription': 'Subscription',+ 'heterogeneousStatus.command.edit': 'Edit command',+ 'heterogeneousStatus.command.label': 'Command',+ 'heterogeneousStatus.command.placeholder': 'Command name or absolute path',+ 'heterogeneousStatus.detecting': `Detecting ${options?.name ?? ''} CLI`,+ 'heterogeneousStatus.plan.label': 'Plan',+ 'heterogeneousStatus.redetect': 'Re-detect',+ 'heterogeneousStatus.unavailable': `${options?.name ?? ''} CLI is unavailable`,+ }) as Record<string, string>+ )[key] || key,+ }),+}));++vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({+ default: ({ agentType }: { agentType?: string }) => (+ <div>{`${agentType ?? 'codex'} Install Guide`}</div>+ ),+}));++vi.mock('@/services/electron/toolDetector', () => ({+ toolDetectorService: {+ detectHeterogeneousAgentCommand,+ getClaudeAuthStatus,+ },+}));++describe('HeterogeneousAgentStatusCard', () => {+ it('shows the embedded Codex install guide when the CLI is unavailable', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });+ getClaudeAuthStatus.mockResolvedValue(null);++ const provider = {+ command: 'codex',+ type: 'codex',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({+ agentType: 'codex',+ command: 'codex',+ });+ });++ expect(screen.getByText('Codex CLI')).toBeInTheDocument();+ expect(screen.getByText('Codex CLI is unavailable')).toBeInTheDocument();+ expect(screen.getByText('codex Install Guide')).toBeInTheDocument();+ expect(screen.getByText('codex')).toBeInTheDocument();+ expect(screen.queryByDisplayValue('codex')).not.toBeInTheDocument();+ });++ it('shows the embedded Claude Code install guide when the CLI is unavailable', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });+ getClaudeAuthStatus.mockResolvedValue(null);++ const provider = {+ command: 'claude',+ type: 'claude-code',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({+ agentType: 'claude-code',+ command: 'claude',+ });+ });++ expect(screen.getByText('Claude Code CLI')).toBeInTheDocument();+ expect(screen.getByText('Claude Code CLI is unavailable')).toBeInTheDocument();+ expect(screen.getByText('claude-code Install Guide')).toBeInTheDocument();+ });++ it('detects and queries auth with the customized Claude command', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({+ available: true,+ path: '/Users/test/bin/claude-alt',+ version: '2.1.118 (Claude Code)',+ });+ getClaudeAuthStatus.mockResolvedValue({+ apiProvider: 'firstParty',+ authMethod: 'claude.ai',+ email: '[email protected]',+ loggedIn: true,+ subscriptionType: 'max',+ });++ const provider = {+ command: 'claude-alt',+ type: 'claude-code',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({+ agentType: 'claude-code',+ command: 'claude-alt',+ });+ });++ await waitFor(() => {+ expect(getClaudeAuthStatus).toHaveBeenCalledWith('claude-alt');+ });++ expect(screen.getByText('claude-alt')).toBeInTheDocument();+ expect(screen.getByText('Auth Method')).toBeInTheDocument();+ expect(screen.getByText('Subscription')).toBeInTheDocument();+ expect(screen.getByText('Plan')).toBeInTheDocument();+ expect(screen.getByText('MAX')).toBeInTheDocument();+ expect(screen.getByText('[email protected]')).toBeInTheDocument();+ });++ it('hides the install guide when a customized command is unavailable', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });+ getClaudeAuthStatus.mockResolvedValue(null);++ const provider = {+ command: 'claude-alt',+ type: 'claude-code',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(screen.getByText('Claude Code CLI is unavailable')).toBeInTheDocument();+ });++ expect(screen.queryByText('claude-code Install Guide')).not.toBeInTheDocument();+ expect(screen.getByText('claude-alt')).toBeInTheDocument();+ });++ it('persists command edits on blur', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: true });+ getClaudeAuthStatus.mockResolvedValue(null);+ const onCommandChange = vi.fn();++ const provider = {+ command: 'codex',+ type: 'codex',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} onCommandChange={onCommandChange} />+ </MemoryRouter>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Edit command' }));++ const input = await screen.findByDisplayValue('codex');+ fireEvent.change(input, { target: { value: 'codex-alt' } });+ fireEvent.blur(input);++ await waitFor(() => {+ expect(onCommandChange).toHaveBeenCalledWith('codex-alt');+ });+ });++ it('keeps the command read-only until edit mode is activated', async () => {+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: true });+ getClaudeAuthStatus.mockResolvedValue(null);++ const provider = {+ command: 'claude',+ type: 'claude-code',+ } satisfies HeterogeneousProviderConfig;++ render(+ <MemoryRouter>+ <HeterogeneousAgentStatusCard provider={provider} />+ </MemoryRouter>,+ );++ expect(await screen.findByText('claude')).toBeInTheDocument();+ expect(screen.queryByDisplayValue('claude')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Edit command' }));++ expect(await screen.findByDisplayValue('claude')).toBeInTheDocument();+ });+});diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsxnew file mode 100644index 00000000000..268385f21e7--- /dev/null+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx@@ -0,0 +1,537 @@+'use client';++import { isDesktop } from '@lobechat/const';+import { type ClaudeAuthStatus, type ToolStatus } from '@lobechat/electron-client-ipc';+import { getHeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';+import type { HeterogeneousProviderConfig } from '@lobechat/types';+import { ActionIcon, CopyButton, Flexbox, Icon, Input, Tag, Text, Tooltip } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { Loader2Icon, PencilLine, RefreshCw, XCircle } from 'lucide-react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';+import { toolDetectorService } from '@/services/electron/toolDetector';++const COMMAND_LINE_HEIGHT = 28;++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ padding-block: 16px 4px;+ padding-inline: 16px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};+ `,+ cardHeader: css`+ display: flex;+ gap: 12px;+ align-items: flex-start;+ justify-content: space-between;+ `,+ cardTitleWrap: css`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 8px;++ min-width: 0;+ `,+ cardTitle: css`+ display: flex;+ gap: 8px;+ align-items: center;+ `,+ metaRow: css`+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;++ min-width: 0;+ `,+ metaText: css`+ font-size: 13px;+ color: ${token.colorTextSecondary};+ `,+ pathWrap: css`+ display: flex;+ gap: 4px;+ align-items: center;++ min-width: 0;+ max-width: 100%;+ `,+ detailList: css`+ margin-block-start: 4px;+ border-block-start: 1px solid ${token.colorBorderSecondary};+ `,+ detailRow: css`+ display: flex;+ gap: 16px;+ align-items: center;++ min-height: 48px;+ padding-block: 8px;++ & + & {+ border-block-start: 1px solid ${token.colorBorderSecondary};+ }+ `,+ detailLabel: css`+ flex-shrink: 0;++ width: 96px;++ font-size: 12px;+ color: ${token.colorTextTertiary};+ text-transform: uppercase;+ letter-spacing: 0.04em;+ `,+ detailContent: css`+ display: flex;+ flex: 1;+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;++ min-width: 0;+ height: ${COMMAND_LINE_HEIGHT}px;+ `,+ commandField: css`+ &:hover .command-edit-button {+ pointer-events: auto;+ opacity: 1;+ }+ `,+ commandInput: css`+ width: 100%;+ font-family: ${token.fontFamilyCode};++ &,+ &.ant-input,+ &.ant-input-affix-wrapper,+ &.ant-input-outlined,+ & input,+ & .ant-input,+ & .ant-input-affix-wrapper,+ & .ant-input-outlined {+ box-sizing: border-box;+ height: ${COMMAND_LINE_HEIGHT}px;+ min-height: ${COMMAND_LINE_HEIGHT}px;+ max-height: ${COMMAND_LINE_HEIGHT}px;+ border-radius: 999px !important;++ font-family: ${token.fontFamilyCode};+ font-size: 14px;+ line-height: ${COMMAND_LINE_HEIGHT - 2}px;+ }++ &,+ &.ant-input,+ &.ant-input-outlined,+ & input,+ & .ant-input,+ & .ant-input-outlined {+ padding-block: 0;+ padding-inline: 12px;+ }++ &.ant-input-affix-wrapper,+ & .ant-input-affix-wrapper {+ overflow: hidden;+ padding-block: 0;+ padding-inline: 12px;+ }++ &.ant-input-affix-wrapper input,+ & .ant-input-affix-wrapper input {+ height: ${COMMAND_LINE_HEIGHT - 2}px;+ padding: 0;+ border-radius: 999px !important;+ line-height: ${COMMAND_LINE_HEIGHT - 2}px;+ }+ `,+ commandInputWrap: css`+ display: flex;+ align-items: center;++ width: min(320px, 100%);+ max-width: 100%;+ height: ${COMMAND_LINE_HEIGHT}px;+ `,+ commandDisplay: css`+ display: inline-flex;+ align-items: center;++ box-sizing: border-box;+ max-width: 100%;+ height: ${COMMAND_LINE_HEIGHT}px;+ padding-block: 0;+ padding-inline: 12px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: 999px;++ background: ${token.colorFillSecondary};+ `,+ commandEditButton: css`+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.2s ease;+ `,+ commandText: css`+ min-width: 0;++ font-family: ${token.fontFamilyCode};+ font-size: 14px;+ line-height: 20px;+ color: ${token.colorText};+ `,+ accountValue: css`+ font-size: 15px;+ color: ${token.colorText};+ `,+ path: css`+ font-family: ${token.fontFamilyCode};+ font-size: 12px;+ color: ${token.colorTextTertiary};+ `,+ unavailableText: css`+ font-size: 13px;+ color: ${token.colorTextSecondary};+ `,+}));++interface HeterogeneousAgentStatusCardProps {+ onCommandChange?: (command: string) => Promise<void> | void;+ provider: HeterogeneousProviderConfig;+}++const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(+ ({ provider, onCommandChange }) => {+ const { t } = useTranslation('setting');+ const { styles } = useStyles();+ const navigate = useNavigate();+ const providerConfig = getHeterogeneousAgentClientConfig(provider.type);+ const defaultCommand = providerConfig?.command || '';+ const resolvedCommand = provider.command?.trim() || defaultCommand;+ const isUsingCustomCommand = resolvedCommand !== defaultCommand;+ const [status, setStatus] = useState<ToolStatus | undefined>();+ const [auth, setAuth] = useState<ClaudeAuthStatus | null>(null);+ const [commandInput, setCommandInput] = useState(resolvedCommand);+ const [detecting, setDetecting] = useState(true);+ const [isEditingCommand, setIsEditingCommand] = useState(false);+ const [savingCommand, setSavingCommand] = useState(false);+ const commandInputRef = useRef<HTMLInputElement | null>(null);++ const displayName = providerConfig?.title || provider.type;+ const AgentIcon = providerConfig?.icon;+ const showCliInstallGuide =+ (provider.type === 'claude-code' || provider.type === 'codex') &&+ !detecting &&+ !status?.available &&+ !isUsingCustomCommand;++ const fetchAuth = useCallback(async () => {+ if (provider.type !== 'claude-code') {+ setAuth(null);+ return;+ }++ try {+ const result = await toolDetectorService.getClaudeAuthStatus(resolvedCommand);+ setAuth(result);+ } catch (error) {+ console.warn('[HeterogeneousAgentStatusCard] Failed to get Claude auth status:', error);+ setAuth(null);+ }+ }, [provider.type, resolvedCommand]);++ const detect = useCallback(async () => {+ if (!isDesktop || !resolvedCommand) {+ setDetecting(false);+ return;+ }++ setDetecting(true);+ try {+ const result = await toolDetectorService.detectHeterogeneousAgentCommand({+ agentType: provider.type,+ command: resolvedCommand,+ });+ setStatus(result);+ if (result.available) {+ void fetchAuth();+ } else {+ setAuth(null);+ }+ } catch (error) {+ console.error('[HeterogeneousAgentStatusCard] Failed to detect CLI:', error);+ setStatus({ available: false, error: (error as Error).message });+ setAuth(null);+ } finally {+ setDetecting(false);+ }+ }, [fetchAuth, provider.type, resolvedCommand]);++ useEffect(() => {+ void detect();+ }, [detect]);++ useEffect(() => {+ setCommandInput(resolvedCommand);+ }, [resolvedCommand]);++ useEffect(() => {+ if (!isEditingCommand) return;++ const focusCommandInput = () => {+ commandInputRef.current?.focus();+ commandInputRef.current?.select();+ };++ const timer = window.setTimeout(focusCommandInput, 0);++ return () => {+ window.clearTimeout(timer);+ };+ }, [isEditingCommand]);++ const startEditingCommand = useCallback(() => {+ if (savingCommand) return;++ setCommandInput(resolvedCommand);+ setIsEditingCommand(true);+ }, [resolvedCommand, savingCommand]);++ const cancelEditingCommand = useCallback(() => {+ setCommandInput(resolvedCommand);+ setIsEditingCommand(false);+ }, [resolvedCommand]);++ const commitCommand = useCallback(async () => {+ const normalizedCommand = commandInput.trim() || defaultCommand;+ setCommandInput(normalizedCommand);++ if (!normalizedCommand || normalizedCommand === resolvedCommand || savingCommand) {+ setIsEditingCommand(false);+ return;+ }++ try {+ setSavingCommand(true);+ await onCommandChange?.(normalizedCommand);+ setIsEditingCommand(false);+ } finally {+ setSavingCommand(false);+ }+ }, [commandInput, defaultCommand, onCommandChange, resolvedCommand, savingCommand]);++ const renderStatusTag = () => {+ if (detecting) {+ return (+ <Tag color="default" style={{ marginInlineEnd: 0 }}>+ {t('settingSystemTools.detecting')}+ </Tag>+ );+ }++ if (!status || !status.available) {+ return (+ <Tag color="error" style={{ marginInlineEnd: 0 }}>+ {t('settingSystemTools.status.unavailable')}+ </Tag>+ );+ }++ return (+ <Tag color="success" style={{ marginInlineEnd: 0 }}>+ {t('settingSystemTools.status.available')}+ </Tag>+ );+ };++ const renderStatusMeta = () => {+ if (detecting) {+ return (+ <Flexbox horizontal align="center" gap={8}>+ <Icon spin icon={Loader2Icon} size={16} style={{ opacity: 0.6 }} />+ <Text className={styles.metaText}>+ {t('heterogeneousStatus.detecting', { name: displayName })}+ </Text>+ </Flexbox>+ );+ }++ if (!status || !status.available) {+ return (+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>+ <Icon color="var(--ant-color-error)" icon={XCircle} size={16} />+ <Text className={styles.unavailableText}>+ {t('heterogeneousStatus.unavailable', { name: displayName })}+ </Text>+ </Flexbox>+ );+ }++ return (+ <Flexbox horizontal align="center" className={styles.metaRow} gap={8}>+ {status.version && (+ <Tag color="processing" style={{ marginInlineEnd: 0 }}>+ {status.version}+ </Tag>+ )}+ {status.path && (+ <Tooltip title={status.path}>+ <Flexbox horizontal align="center" className={styles.pathWrap} gap={4}>+ <Text ellipsis className={styles.path}>+ {status.path}+ </Text>+ <CopyButton content={status.path} size="small" />+ </Flexbox>+ </Tooltip>+ )}+ </Flexbox>+ );+ };++ const renderCommandEditor = () => {+ return (+ <div className={`${styles.detailRow} ${styles.commandField}`}>+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.command.label')}</Text>+ <div className={styles.detailContent}>+ {isEditingCommand ? (+ <div className={styles.commandInputWrap}>+ <Input+ className={styles.commandInput}+ disabled={savingCommand}+ placeholder={t('heterogeneousStatus.command.placeholder')}+ ref={commandInputRef as never}+ value={commandInput}+ onBlur={() => {+ void commitCommand();+ }}+ onChange={(event) => {+ setCommandInput(event.target.value);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ cancelEditingCommand();+ return;+ }++ if (event.key === 'Enter') {+ event.preventDefault();+ void commitCommand();+ }+ }}+ />+ </div>+ ) : (+ <div className={styles.commandDisplay}>+ <Text ellipsis className={styles.commandText}>+ {resolvedCommand}+ </Text>+ </div>+ )}+ {!isEditingCommand && !savingCommand && (+ <Tooltip title={t('heterogeneousStatus.command.edit')}>+ <ActionIcon+ aria-label={t('heterogeneousStatus.command.edit')}+ className={`command-edit-button ${styles.commandEditButton}`}+ icon={PencilLine}+ size="small"+ onClick={startEditingCommand}+ />+ </Tooltip>+ )}+ </div>+ </div>+ );+ };++ const renderAuth = () => {+ if (provider.type !== 'claude-code' || detecting || !status?.available || !auth?.loggedIn)+ return null;++ const authMode =+ auth.authMethod === 'claude.ai' || auth.apiProvider === 'firstParty'+ ? t('heterogeneousStatus.auth.subscription')+ : t('heterogeneousStatus.auth.api');++ return (+ <>+ <div className={styles.detailRow}>+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.auth.label')}</Text>+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>+ <Text className={styles.accountValue}>{authMode}</Text>+ </Flexbox>+ </div>+ <div className={styles.detailRow}>+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.account.label')}</Text>+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>+ {auth.email && (+ <Text ellipsis className={styles.accountValue}>+ {auth.email}+ </Text>+ )}+ </Flexbox>+ </div>+ {auth.subscriptionType && (+ <div className={styles.detailRow}>+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.plan.label')}</Text>+ <Flexbox horizontal align="center" gap={8} style={{ flexWrap: 'wrap' }}>+ <Text className={styles.accountValue}>{auth.subscriptionType.toUpperCase()}</Text>+ </Flexbox>+ </div>+ )}+ </>+ );+ };++ return (+ <Flexbox className={styles.card} gap={12}>+ <div className={styles.cardHeader}>+ <div className={styles.cardTitleWrap}>+ <div className={styles.cardTitle}>+ {AgentIcon && <AgentIcon size={16} />}+ <Text strong>{`${displayName} CLI`}</Text>+ </div>+ <div className={styles.metaRow}>+ {renderStatusTag()}+ {renderStatusMeta()}+ </div>+ </div>+ <Tooltip title={t('heterogeneousStatus.redetect')}>+ <ActionIcon+ aria-label={t('heterogeneousStatus.redetect')}+ disabled={detecting}+ icon={RefreshCw}+ loading={detecting}+ size="small"+ onClick={detect}+ />+ </Tooltip>+ </div>+ <div className={styles.detailList}>+ {renderCommandEditor()}+ {renderAuth()}+ </div>+ {showCliInstallGuide && (+ <HeterogeneousAgentStatusGuide+ agentType={provider.type}+ variant={'embedded'}+ onOpenSystemTools={() => navigate('/settings/system-tools')}+ />+ )}+ </Flexbox>+ );+ },+);++HeterogeneousAgentStatusCard.displayName = 'HeterogeneousAgentStatusCard';++export default HeterogeneousAgentStatusCard;diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 636e6b04bc0..c12d1a3fd71 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -15,13 +15,26 @@ import AgentSettings from '../AgentSettings';import EditorCanvas from '../EditorCanvas';import AgentHeader from './AgentHeader';import AgentTool from './AgentTool';-import CCStatusCard from './CCStatusCard';+import HeterogeneousAgentStatusCard from './HeterogeneousAgentStatusCard';const ProfileEditor = memo(() => {const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);const updateConfig = useAgentStore((s) => s.updateAgentConfig);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);+ const heterogeneousProvider = config.agencyConfig?.heterogeneousProvider;+ const updateHeterogeneousCommand = async (command: string) => {+ if (!heterogeneousProvider) return;++ await updateConfig({+ agencyConfig: {+ heterogeneousProvider: {+ ...heterogeneousProvider,+ command,+ },+ },+ });+ };return (<>@@ -33,9 +46,12 @@ const ProfileEditor = memo(() => {>{/* Header: Avatar + Name + Description */}<AgentHeader />- {isHeterogeneous ? (- // CC integration mode: show CLI version + path instead of model/skills pickers- <CCStatusCard />+ {isHeterogeneous && heterogeneousProvider ? (+ // Heterogeneous integration mode: show provider CLI status instead of model/skills pickers+ <HeterogeneousAgentStatusCard+ provider={heterogeneousProvider}+ onCommandChange={updateHeterogeneousCommand}+ />) : (<>{/* Config Bar: Model Selector */}diff --git a/src/routes/(main)/home/_layout/Body/Agent/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/index.tsxindex 6119e512401..c48e8b95713 100644--- a/src/routes/(main)/home/_layout/Body/Agent/index.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/index.tsx@@ -25,17 +25,24 @@ const Agent = memo<AgentProps>(({ itemKey }) => {const { openConfigGroupModal } = useAgentModal();// Create menu items- const { createAgentMenuItem, createClaudeCodeMenuItem, createGroupChatMenuItem, isLoading } =- useCreateMenuItems();+ const {+ createAgentMenuItem,+ createGroupChatMenuItem,+ createHeterogeneousAgentMenuItems,+ isLoading,+ } = useCreateMenuItems();const addMenuItems = useMemo(() => {- const ccItem = createClaudeCodeMenuItem();+ const heterogeneousItems = createHeterogeneousAgentMenuItems();+return [createAgentMenuItem(),createGroupChatMenuItem(),- ...(ccItem ? [{ type: 'divider' as const }, ccItem] : []),+ ...(heterogeneousItems.length > 0+ ? [{ type: 'divider' as const }, ...heterogeneousItems]+ : []),];- }, [createAgentMenuItem, createClaudeCodeMenuItem, createGroupChatMenuItem]);+ }, [createAgentMenuItem, createGroupChatMenuItem, createHeterogeneousAgentMenuItems]);const handleOpenConfigGroupModal = useCallback(() => {openConfigGroupModal();diff --git a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx b/src/routes/(main)/home/_layout/Header/components/AddButton.tsxindex 5e14c53a591..ce1f084e37b 100644--- a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx+++ b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx@@ -15,8 +15,8 @@ const AddButton = memo(() => {// Create menu itemsconst {createAgentMenuItem,- createClaudeCodeMenuItem,createGroupChatMenuItem,+ createHeterogeneousAgentMenuItems,createPageMenuItem,openCreateModal,isMutatingAgent,@@ -33,14 +33,22 @@ const AddButton = memo(() => {);const dropdownItems = useMemo(() => {- const ccItem = createClaudeCodeMenuItem();+ const heterogeneousItems = createHeterogeneousAgentMenuItems();+return [createAgentMenuItem(),createGroupChatMenuItem(),createPageMenuItem(),- ...(ccItem ? [{ type: 'divider' as const }, ccItem] : []),+ ...(heterogeneousItems.length > 0+ ? [{ type: 'divider' as const }, ...heterogeneousItems]+ : []),];- }, [createAgentMenuItem, createClaudeCodeMenuItem, createGroupChatMenuItem, createPageMenuItem]);+ }, [+ createAgentMenuItem,+ createGroupChatMenuItem,+ createHeterogeneousAgentMenuItems,+ createPageMenuItem,+ ]);return (<Flexbox horizontal>diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsxnew file mode 100644index 00000000000..93cba885259--- /dev/null+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx@@ -0,0 +1,217 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useCreateMenuItems } from './useCreateMenuItems';++const createAgentMock = vi.hoisted(() => vi.fn().mockResolvedValue({ agentId: 'agent-codex' }));+const refreshAgentListMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const addGroupMock = vi.hoisted(() => vi.fn());+const switchToGroupMock = vi.hoisted(() => vi.fn());+const createGroupMock = vi.hoisted(() => vi.fn());+const loadGroupsMock = vi.hoisted(() => vi.fn());+const createNewPageMock = vi.hoisted(() => vi.fn());+const messageErrorMock = vi.hoisted(() => vi.fn());+const navigateMock = vi.hoisted(() => vi.fn());++vi.mock('@lobechat/const', () => ({+ isDesktop: true,+}));++vi.mock('@lobechat/heterogeneous-agents/client', () => ({+ HETEROGENEOUS_AGENT_CLIENT_CONFIGS: [+ {+ avatar: 'claude-avatar',+ command: 'claude',+ icon: () => null,+ iconId: 'ClaudeCode',+ menuKey: 'newClaudeCodeAgent',+ menuLabelKey: 'newClaudeCodeAgent',+ title: 'Claude Code',+ type: 'claude-code',+ },+ {+ avatar: 'avatar',+ command: 'codex',+ icon: () => null,+ iconId: 'Codex',+ menuKey: 'newCodexAgent',+ menuLabelKey: 'newCodexAgent',+ title: 'Codex',+ type: 'codex',+ },+ ],+}));++vi.mock('@lobehub/ui', () => ({+ Icon: () => null,+}));++vi.mock('@lobehub/ui/icons', () => ({+ GroupBotSquareIcon: () => null,+}));++vi.mock('antd', () => ({+ App: {+ useApp: () => ({+ message: { error: messageErrorMock },+ notification: { error: vi.fn() },+ }),+ },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('react-router-dom', () => ({+ useNavigate: () => navigateMock,+}));++vi.mock('swr/mutation', () => ({+ default: () => ({+ isMutating: false,+ trigger: vi.fn(),+ }),+}));++vi.mock('@/components/ChatGroupWizard/templates', () => ({+ useGroupTemplates: () => [],+}));++vi.mock('@/routes/(main)/home/_layout/Body/Agent/ModalProvider', () => ({+ useOptionalAgentModal: () => undefined,+}));++vi.mock('@/services/chatGroup', () => ({+ chatGroupService: {+ createGroupWithMembers: vi.fn(),+ },+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ createAgent: createAgentMock,+ }),+}));++vi.mock('@/store/agentGroup', () => ({+ useAgentGroupStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ createGroup: createGroupMock,+ loadGroups: loadGroupsMock,+ }),+}));++vi.mock('@/store/home', () => ({+ useHomeStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ addGroup: addGroupMock,+ refreshAgentList: refreshAgentListMock,+ switchToGroup: switchToGroupMock,+ }),+}));++vi.mock('@/store/page', () => ({+ usePageStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ createNewPage: createNewPageMock,+ }),+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ enableHeterogeneousAgent: true,+ }),+}));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: {+ enableHeterogeneousAgent: (state: Record<string, boolean>) => state.enableHeterogeneousAgent,+ },+}));++const isActionItem = (+ item: unknown,+): item is {+ key: string;+ onClick?: (info: { domEvent?: { stopPropagation?: () => void } }) => Promise<void>;+} => !!item && typeof item === 'object' && 'key' in item;++describe('useCreateMenuItems', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('creates the Claude Code agent normally when the CLI is available', async () => {+ const { result } = renderHook(() => useCreateMenuItems());++ const claudeItem = result.current+ .createHeterogeneousAgentMenuItems()+ .find((item) => isActionItem(item) && item.key === 'newClaudeCodeAgent');++ if (!isActionItem(claudeItem)) {+ throw new Error('Expected Claude Code menu item');+ }++ await act(async () => {+ await claudeItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });+ });++ expect(createAgentMock).toHaveBeenCalledWith({+ config: {+ agencyConfig: {+ heterogeneousProvider: {+ command: 'claude',+ type: 'claude-code',+ },+ },+ avatar: 'claude-avatar',+ systemRole: '',+ title: 'Claude Code',+ },+ groupId: undefined,+ });+ expect(refreshAgentListMock).toHaveBeenCalled();+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-codex');+ });++ it('creates the Codex agent normally without preflight interception', async () => {+ const { result } = renderHook(() => useCreateMenuItems());++ const codexItem = result.current+ .createHeterogeneousAgentMenuItems()+ .find((item) => isActionItem(item) && item.key === 'newCodexAgent');++ if (!isActionItem(codexItem)) {+ throw new Error('Expected Codex menu item');+ }++ await act(async () => {+ await codexItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });+ });++ expect(createAgentMock).toHaveBeenCalledWith({+ config: {+ agencyConfig: {+ heterogeneousProvider: {+ command: 'codex',+ type: 'codex',+ },+ },+ avatar: 'avatar',+ systemRole: '',+ title: 'Codex',+ },+ groupId: undefined,+ });+ expect(refreshAgentListMock).toHaveBeenCalled();+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-codex');+ });+});diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsxindex d60d2d984a9..694888e8126 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx@@ -1,9 +1,9 @@import { isDesktop } from '@lobechat/const';-import { ClaudeCode } from '@lobehub/icons';+import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';import { Icon } from '@lobehub/ui';import { GroupBotSquareIcon } from '@lobehub/ui/icons';import { App } from 'antd';-import { type ItemType } from 'antd/es/menu/interface';+import type { ItemType } from 'antd/es/menu/interface';import { BotIcon, FileTextIcon, FolderCogIcon, FolderPlus } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -13,8 +13,8 @@ import useSWRMutation from 'swr/mutation';import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';import { useOptionalAgentModal } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';-import { type CreateAgentParams } from '@/services/agent';-import { type GroupMemberConfig } from '@/services/chatGroup';+import type { CreateAgentParams } from '@/services/agent';+import type { GroupMemberConfig } from '@/services/chatGroup';import { chatGroupService } from '@/services/chatGroup';import { useAgentStore } from '@/store/agent';import { useAgentGroupStore } from '@/store/agentGroup';@@ -198,25 +198,27 @@ export const useCreateMenuItems = () => {);/**- * Create a Claude Code agent with ACP provider pre-configured.+ * Create a heterogeneous agent with CLI provider pre-configured.** Bypasses `mutateAgent` so we skip its default /profile redirect —- * CC agents land straight on the chat page since their config is fixed.+ * external CLI agents land straight on the chat page since their config is fixed.*/- const createClaudeCodeAgent = useCallback(- async (options?: CreateAgentOptions) => {+ const createHeterogeneousAgent = useCallback(+ async (+ definition: (typeof HETEROGENEOUS_AGENT_CLIENT_CONFIGS)[number],+ options?: CreateAgentOptions,+ ) => {const result = await storeCreateAgent({config: {agencyConfig: {heterogeneousProvider: {- command: 'claude',- type: 'claude-code' as const,+ command: definition.command,+ type: definition.type,},},- avatar:- 'https://registry.npmmirror.com/@lobehub/icons-static-avatar/latest/files/avatars/claudecode.webp',+ avatar: definition.avatar,systemRole: '',- title: 'Claude Code',+ title: definition.title,},groupId: options?.groupId,});@@ -253,22 +255,27 @@ export const useCreateMenuItems = () => {);/**- * Create Claude Code agent menu item (Desktop only)+ * Create heterogeneous agent menu items (Desktop only)*/- const createClaudeCodeMenuItem = useCallback(- (options?: CreateAgentOptions): ItemType | null => {- if (!isDesktop || !enableHeterogeneousAgent) return null;- return {- icon: <ClaudeCode size={'1em'} />,- key: 'newClaudeCodeAgent',- label: t('newClaudeCodeAgent'),- onClick: async (info) => {- info.domEvent?.stopPropagation();- await createClaudeCodeAgent(options);- },- };+ const createHeterogeneousAgentMenuItems = useCallback(+ (options?: CreateAgentOptions): ItemType[] => {+ if (!isDesktop || !enableHeterogeneousAgent) return [];++ return HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((definition) => {+ const AgentIcon = definition.icon;++ return {+ icon: <AgentIcon size={'1em'} />,+ key: definition.menuKey,+ label: t(definition.menuLabelKey),+ onClick: async (info) => {+ info.domEvent?.stopPropagation();+ await createHeterogeneousAgent(definition, options);+ },+ };+ });},- [t, createClaudeCodeAgent, enableHeterogeneousAgent],+ [t, createHeterogeneousAgent, enableHeterogeneousAgent],);/**@@ -362,11 +369,11 @@ export const useCreateMenuItems = () => {configMenuItem,createAgent,createAgentMenuItem,- createClaudeCodeAgent,- createClaudeCodeMenuItem,createEmptyGroup,createGroupChatMenuItem,createGroupFromTemplate,+ createHeterogeneousAgent,+ createHeterogeneousAgentMenuItems,createGroupWithMembers,createPage,createPageMenuItem,diff --git a/src/server/services/message/__tests__/index.integration.test.ts b/src/server/services/message/__tests__/index.integration.test.tsindex b375f35d59f..ed0a7080de4 100644--- a/src/server/services/message/__tests__/index.integration.test.ts+++ b/src/server/services/message/__tests__/index.integration.test.ts@@ -11,6 +11,8 @@ import {users,} from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import { MessageGroupType } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -260,6 +262,46 @@ describe('MessageService Integration Tests', () => {expect(result.messages).toHaveLength(1);expect(result.messages![0].content).toBe('updated content');});++ it('should persist message errors and return them in queried messages', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });+ await serverDB.insert(topics).values({ id: 'topic-1', userId, sessionId: 'session-1' });++ await serverDB.insert(messages).values({+ id: 'msg-err-1',+ userId,+ agentId: 'agent-1',+ topicId: 'topic-1',+ role: 'assistant',+ content: '',+ });++ const messageError = {+ body: {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ message: 'Failed to authenticate. API Error: 401',+ },+ message: 'Failed to authenticate. API Error: 401',+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };++ const result = await messageService.updateMessage(+ 'msg-err-1',+ { error: messageError },+ { agentId: 'agent-1', topicId: 'topic-1' },+ );++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].error).toEqual(messageError);+ });});describe('updateMetadata', () => {diff --git a/src/services/electron/toolDetector.ts b/src/services/electron/toolDetector.tsindex ef5e06101ab..cda5088277a 100644--- a/src/services/electron/toolDetector.ts+++ b/src/services/electron/toolDetector.ts@@ -1,5 +1,6 @@import {type ClaudeAuthStatus,+ type DetectHeterogeneousAgentCommandParams,type ToolCategory,type ToolInfo,type ToolStatus,@@ -15,6 +16,12 @@ class ToolDetectorService {return ensureElectronIpc().toolDetector.detectTool(name, force);};+ detectHeterogeneousAgentCommand = async (+ params: DetectHeterogeneousAgentCommandParams,+ ): Promise<ToolStatus> => {+ return ensureElectronIpc().toolDetector.detectHeterogeneousAgentCommand(params);+ };+/*** Detect all registered tools*/@@ -84,8 +91,8 @@ class ToolDetectorService {/*** Get Claude Code CLI auth/account status*/- getClaudeAuthStatus = async (): Promise<ClaudeAuthStatus | null> => {- return ensureElectronIpc().toolDetector.getClaudeAuthStatus();+ getClaudeAuthStatus = async (command = 'claude'): Promise<ClaudeAuthStatus | null> => {+ return ensureElectronIpc().toolDetector.getClaudeAuthStatus(command);};}diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 67b7abecd22..ba5fdcc33fa 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -1,3 +1,4 @@+import type * as LobechatConstModule from '@lobechat/const';import { act, renderHook } from '@testing-library/react';import { TRPCClientError } from '@trpc/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -17,6 +18,23 @@ import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from '.// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');+const executeHeterogeneousAgentMock = vi.hoisted(() => vi.fn());+const mockConstEnv = vi.hoisted(() => ({ isDesktop: false }));++vi.mock('@lobechat/const', async (importOriginal) => {+ const actual = await importOriginal<typeof LobechatConstModule>();+ return {+ ...actual,+ get isDesktop() {+ return mockConstEnv.isDesktop;+ },+ };+});++vi.mock('../heterogeneousAgentExecutor', () => ({+ executeHeterogeneousAgent: (...args: any[]) => executeHeterogeneousAgentMock(...args),+}));+// Mock lambdaClient to prevent network requestsvi.mock('@/libs/trpc/client', () => ({lambdaClient: {@@ -46,6 +64,8 @@ beforeEach(() => {});afterEach(() => {+ executeHeterogeneousAgentMock.mockReset();+ mockConstEnv.isDesktop = false;vi.restoreAllMocks();});@@ -725,6 +745,51 @@ describe('ConversationLifecycle actions', () => {expect.any(AbortController),);});++ it('should not persist the requested model for heterogeneous agents before the CLI reports it', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ model: 'claude-sonnet-4-6',+ },+ });++ const { result } = renderHook(() => useChatStore());++ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ topics: [],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ executeHeterogeneousAgentMock.mockResolvedValue(undefined);++ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(sendMessageInServerSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ newAssistantMessage: {+ provider: 'codex',+ },+ }),+ expect.any(AbortController),+ );+ });});describe('optimistic topic updatedAt', () => {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex ecf7b34cfa5..ef443271a36 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -1,10 +1,15 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';import { createGatewayEventHandler } from '../gatewayEventHandler';vi.mock('@/services/message', () => ({- messageService: { getMessages: vi.fn().mockResolvedValue([]) },+ messageService: {+ getMessages: vi.fn().mockResolvedValue([]),+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),+ },}));// ─── Test Helpers ───@@ -51,6 +56,10 @@ const flush = async () => {// ─── Tests ───describe('createGatewayEventHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+describe('stream_start', () => {it('should associate new message with operation', async () => {const store = createMockStore();@@ -328,6 +337,20 @@ describe('createGatewayEventHandler', () => {undefined,);expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ {+ body: { message: 'Something went wrong' },+ message: 'Something went wrong',+ type: 'AgentRuntimeError',+ },+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: undefined,+ topicId: 'topic-1',+ },+ );// Should dispatch inline error immediatelyexpect(store.internal_dispatchMessage).toHaveBeenCalledWith(@@ -335,13 +358,17 @@ describe('createGatewayEventHandler', () => {id: 'msg-initial',type: 'updateMessage',value: {- error: { body: { message: 'Something went wrong' }, type: 'AgentRuntimeError' },+ error: {+ body: { message: 'Something went wrong' },+ message: 'Something went wrong',+ type: 'AgentRuntimeError',+ },},},{ operationId: 'op-1' },);- // Should also fetch from DB+ // Should also refresh messagesexpect(store.replaceMessages).toHaveBeenCalled();});@@ -358,6 +385,20 @@ describe('createGatewayEventHandler', () => {undefined,);expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-step2',+ {+ body: { message: 'Timeout' },+ message: 'Timeout',+ type: 'AgentRuntimeError',+ },+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: undefined,+ topicId: 'topic-1',+ },+ );// Should dispatch inline error with the switched message IDexpect(store.internal_dispatchMessage).toHaveBeenCalledWith(@@ -365,6 +406,7 @@ describe('createGatewayEventHandler', () => {id: 'msg-step2',value: expect.objectContaining({error: expect.objectContaining({+ message: 'Timeout',body: { message: 'Timeout' },}),}),@@ -373,6 +415,104 @@ describe('createGatewayEventHandler', () => {);expect(store.replaceMessages).toHaveBeenCalled();});++ it('should preserve structured heterogeneous agent error payloads', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ }),+ );+ await flush();++ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ {+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ },+ expect.any(Object),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ value: {+ error: {+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ },+ },+ }),+ { operationId: 'op-1' },+ );+ });++ it('should prefer updateMessageError returned messages over an extra refetch', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];++ vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({+ messages: persistedMessages as any,+ success: true,+ });++ handler(makeEvent('error', { message: 'Something went wrong' }));+ await flush();++ expect(store.replaceMessages).toHaveBeenCalledWith(persistedMessages, {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },+ });+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('should ignore late events after an error so the inline error is not overwritten', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];++ vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({+ messages: persistedMessages as any,+ success: true,+ });++ handler(makeEvent('error', { message: 'Something went wrong' }));+ handler(makeEvent('tool_end', { isSuccess: true }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'late chunk' }));+ await flush();++ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({+ value: { content: 'late chunk' },+ }),+ expect.any(Object),+ );+ expect(store.replaceMessages).toHaveBeenCalledTimes(1);+ });});describe('sequential processing', () => {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heteroResume.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heteroResume.test.tsindex f5ae6931fb6..2e2c03bd640 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heteroResume.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heteroResume.test.ts@@ -24,6 +24,7 @@ describe('resolveHeteroResume', () => {expect(resolveHeteroResume(metadata, '/Users/me/projB')).toEqual({cwdChanged: true,+ reason: 'cwd_changed',resumeSessionId: undefined,});});@@ -48,6 +49,7 @@ describe('resolveHeteroResume', () => {expect(resolveHeteroResume(metadata, undefined)).toEqual({cwdChanged: true,+ reason: 'cwd_changed',resumeSessionId: undefined,});});@@ -62,6 +64,7 @@ describe('resolveHeteroResume', () => {expect(resolveHeteroResume(metadata, '/Users/me/any')).toEqual({cwdChanged: true,+ reason: 'missing_bound_cwd',resumeSessionId: undefined,});});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex c397592f377..0fab298264c 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -9,9 +9,13 @@* - Content/reasoning/model/usage final writes* - Sync snapshot + reset to prevent cross-step content contamination*/+import path from 'node:path';++import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createGatewayEventHandler } from '../gatewayEventHandler';+import type { HeterogeneousAgentExecutorParams } from '../heterogeneousAgentExecutor';import { executeHeterogeneousAgent } from '../heterogeneousAgentExecutor';// ─── Mocks ───@@ -19,6 +23,7 @@ import { executeHeterogeneousAgent } from '../heterogeneousAgentExecutor';// messageService — the DB layer under testconst mockCreateMessage = vi.fn();const mockUpdateMessage = vi.fn();+const mockUpdateMessageError = vi.fn();const mockUpdateToolMessage = vi.fn();const mockGetMessages = vi.fn();@@ -27,6 +32,7 @@ vi.mock('@/services/message', () => ({createMessage: (...args: any[]) => mockCreateMessage(...args),getMessages: (...args: any[]) => mockGetMessages(...args),updateMessage: (...args: any[]) => mockUpdateMessage(...args),+ updateMessageError: (...args: any[]) => mockUpdateMessageError(...args),updateToolMessage: (...args: any[]) => mockUpdateToolMessage(...args),},}));@@ -90,7 +96,7 @@ function setupIpcCapture() {handler?.(null, { sessionId });},/** Simulate session error */- emitError: (sessionId: string, error: string) => {+ emitError: (sessionId: string, error: Record<string, unknown> | string) => {const handler = listeners.get('heteroAgentSessionError');handler?.(null, { error, sessionId });},@@ -107,6 +113,7 @@ function createMockStore(overrides: Record<string, any> = {}) {completeOperation: vi.fn(),internal_dispatchMessage: vi.fn(),internal_toggleToolCallingStreaming: vi.fn(),+ refreshMessages: vi.fn(async () => {}),refreshThreads: vi.fn(async () => {}),replaceMessages: vi.fn(),startOperation: vi.fn(() => {@@ -116,6 +123,7 @@ function createMockStore(overrides: Record<string, any> = {}) {operationId: `sub-op-${subOpCounter}`,};}),+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),...overrides,} as any;}@@ -126,7 +134,7 @@ const defaultContext = {topicId: 'topic-1',};-const defaultParams = {+const defaultParams: HeterogeneousAgentExecutorParams = {assistantMessageId: 'ast-initial',context: defaultContext,heterogeneousProvider: { command: 'claude', type: 'claude-code' as const },@@ -249,6 +257,59 @@ const ccMessageDelta = (usage: {type: 'stream_event',});+// ─── Codex JSONL event factories ───++const codexThreadStarted = (threadId = 'codex-thread-1') => ({+ thread_id: threadId,+ type: 'thread.started',+});++const codexTurnStarted = () => ({+ type: 'turn.started',+});++const codexAgentMessage = (id: string, text: string) => ({+ item: {+ id,+ text,+ type: 'agent_message',+ },+ type: 'item.completed',+});++const codexCommandStarted = (id: string, command: string) => ({+ item: {+ aggregated_output: '',+ command,+ exit_code: null,+ id,+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+});++const codexCommandCompleted = (id: string, command: string, aggregatedOutput: string) => ({+ item: {+ aggregated_output: aggregatedOutput,+ command,+ exit_code: 0,+ id,+ status: 'completed',+ type: 'command_execution',+ },+ type: 'item.completed',+});++const codexTurnCompleted = (usage?: {+ cached_input_tokens?: number;+ input_tokens?: number;+ output_tokens?: number;+}) => ({+ ...(usage ? { usage } : {}),+ type: 'turn.completed',+});+// ─── Tests ───describe('heterogeneousAgentExecutor DB persistence', () => {@@ -266,6 +327,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {id: `created-${params.role}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,}));mockUpdateMessage.mockResolvedValue(undefined);+ mockUpdateMessageError.mockResolvedValue({ success: false });mockUpdateToolMessage.mockResolvedValue(undefined);mockCreateThread.mockImplementation(async (params: any) => params.id || 'thread-generated');});@@ -728,6 +790,598 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);expect(contentWrite).toBeDefined();});++ it('should not persist streamed auth error echoes as assistant content when the session errors', async () => {+ const rawAuthError =+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';++ const store = createMockStore();+ const get = vi.fn(() => store);++ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, defaultParams);+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', rawAuthError));+ ipc.emitError('ipc-sess-1', rawAuthError);+ await flush();++ resolveSendPrompt!();+ await executorPromise.catch(() => {});+ await flush();++ const contentWrite = mockUpdateMessage.mock.calls.find(+ ([id, val]: any) => id === 'ast-initial' && val.content === rawAuthError,+ );++ expect(contentWrite).toBeUndefined();+ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ expect.any(Object),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'ast-initial',+ type: 'updateMessage',+ value: {+ content: '',+ error: {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ },+ },+ { operationId: 'op-1' },+ );+ });++ it('should not keep streamed auth error echoes when the adapter ends with a result error', async () => {+ const rawAuthError =+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';++ const { store } = await runWithEvents([+ ccInit(),+ ccText('msg_01', rawAuthError),+ ccResult(true, rawAuthError),+ ]);++ const contentWrite = mockUpdateMessage.mock.calls.find(+ ([id, val]: any) => id === 'ast-initial' && val.content === rawAuthError,+ );++ expect(contentWrite).toBeUndefined();+ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ expect.any(Object),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'ast-initial',+ type: 'updateMessage',+ value: {+ content: '',+ error: {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ },+ },+ { operationId: 'op-1' },+ );+ });++ it('should prefer deferred adapter auth errors over generic exit-code session errors', async () => {+ const rawAuthError =+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';++ const store = createMockStore();+ const get = vi.fn(() => store);++ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, defaultParams);+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', rawAuthError));+ ipc.emitRawLine('ipc-sess-1', ccResult(true, rawAuthError));+ ipc.emitError('ipc-sess-1', 'Agent exited with code 1');+ await flush();++ resolveSendPrompt!();+ await executorPromise.catch(() => {});+ await flush();++ const contentWrite = mockUpdateMessage.mock.calls.find(+ ([id, val]: any) => id === 'ast-initial' && val.content === rawAuthError,+ );++ expect(contentWrite).toBeUndefined();+ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ expect.any(Object),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'ast-initial',+ type: 'updateMessage',+ value: {+ content: '',+ error: {+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ stderr: rawAuthError,+ }),+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ type: 'AgentRuntimeError',+ },+ },+ },+ { operationId: 'op-1' },+ );+ });++ it('should persist and dispatch structured cli-not-found errors when sendPrompt rejects', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ const cliError = {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',+ installCommands: ['curl -fsSL https://claude.ai/install.sh | bash'],+ message: 'Claude Code CLI was not found',+ };++ mockSendPrompt.mockRejectedValueOnce(cliError);++ await executeHeterogeneousAgent(get, defaultParams);+ await flush();++ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ {+ body: cliError,+ message: 'Claude Code CLI was not found',+ type: 'AgentRuntimeError',+ },+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: undefined,+ topicId: 'topic-1',+ },+ );+ expect(store.refreshMessages).toHaveBeenCalled();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'ast-initial',+ type: 'updateMessage',+ value: {+ error: {+ body: cliError,+ message: 'Claude Code CLI was not found',+ type: 'AgentRuntimeError',+ },+ },+ },+ { operationId: 'op-1' },+ );+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ });++ it('should forward imageList to heterogeneousAgentService.sendPrompt for Codex runs', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ setupIpcCapture();+ const imageList = [+ { id: 'image-1', url: 'https://example.com/screenshot-1.png' },+ { id: 'image-2', url: 'https://example.com/screenshot-2.png' },+ ];++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ imageList,+ });++ expect(mockSendPrompt).toHaveBeenCalledWith('ipc-sess-1', 'test prompt', imageList);+ });++ it('should clear stale resume metadata and retry once without resume for recoverable Codex errors', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ const sendPromptControllers = new Map<+ string,+ { reject: (reason?: unknown) => void; resolve: () => void }+ >();++ mockStartSession+ .mockResolvedValueOnce({ sessionId: 'ipc-sess-1' })+ .mockResolvedValueOnce({ sessionId: 'ipc-sess-2' });+ mockSendPrompt.mockImplementation(+ (sessionId: string) =>+ new Promise<void>((resolve, reject) => {+ sendPromptControllers.set(sessionId, { reject, resolve });+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ resumeSessionId: 'thread_stale_123',+ workingDirectory: '/Users/me/repo',+ });++ await flush();++ ipc.emitError('ipc-sess-1', {+ agentType: 'codex',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ message: 'The saved Codex thread could not be found, so it can no longer be resumed.',+ });+ await flush();++ sendPromptControllers.get('ipc-sess-1')?.reject(new Error('resume failed'));+ await flush();++ expect(mockStartSession).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ agentType: 'codex',+ resumeSessionId: 'thread_stale_123',+ }),+ );+ expect(mockStartSession).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ agentType: 'codex',+ resumeSessionId: undefined,+ }),+ );+ expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: undefined,+ workingDirectory: '/Users/me/repo',+ });++ ipc.emitRawLine('ipc-sess-2', { thread_id: 'thread_new_456', type: 'thread.started' });+ ipc.emitComplete('ipc-sess-2');+ await flush();++ sendPromptControllers.get('ipc-sess-2')?.resolve();+ await executorPromise;+ await flush();++ expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: 'thread_new_456',+ workingDirectory: '/Users/me/repo',+ });+ });+ });++ describe('Codex multi-turn persistence', () => {+ it('should switch to a new assistant before persisting the next turn tool', async () => {+ const idCounter = { assistant: 0, tool: 0 };+ mockCreateMessage.mockImplementation(async (params: any) => {+ if (params.role === 'tool') {+ idCounter.tool += 1;+ return { id: `tool-${idCounter.tool}` };+ }++ if (params.role === 'assistant') {+ idCounter.assistant += 1;+ return { id: `ast-new-${idCounter.assistant}` };+ }++ return { id: `created-${params.role}-${idCounter.assistant + idCounter.tool}` };+ });++ const toolsUpdates: Array<{ assistantId: string; toolIds: string[] }> = [];+ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (val.tools) {+ toolsUpdates.push({+ assistantId: id,+ toolIds: val.tools.map((tool: any) => tool.id),+ });+ }+ });++ await runWithEvents(+ [+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Running the first command.'),+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),+ codexTurnCompleted({ input_tokens: 10, output_tokens: 3 }),+ codexTurnStarted(),+ codexAgentMessage('item_2', 'Running the second command.'),+ codexCommandStarted('item_3', "/bin/zsh -lc 'git status --short'"),+ codexCommandCompleted('item_3', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),+ codexTurnCompleted({ input_tokens: 12, output_tokens: 4 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const secondTurnAssistantCreate = mockCreateMessage.mock.calls.find(+ ([params]: any) => params.role === 'assistant',+ );+ expect(secondTurnAssistantCreate?.[0]).toMatchObject({+ parentId: 'tool-1',+ role: 'assistant',+ });++ const firstToolCreate = mockCreateMessage.mock.calls.find(+ ([params]: any) => params.role === 'tool' && params.tool_call_id === 'item_1',+ );+ expect(firstToolCreate?.[0]).toMatchObject({+ parentId: 'ast-initial',+ role: 'tool',+ tool_call_id: 'item_1',+ });++ const secondToolCreate = mockCreateMessage.mock.calls.find(+ ([params]: any) => params.role === 'tool' && params.tool_call_id === 'item_3',+ );+ expect(secondToolCreate?.[0]).toMatchObject({+ parentId: 'ast-new-1',+ role: 'tool',+ tool_call_id: 'item_3',+ });++ const firstTurnToolWrites = toolsUpdates.filter(+ (update) => update.assistantId === 'ast-initial' && update.toolIds.includes('item_1'),+ );+ expect(firstTurnToolWrites.length).toBeGreaterThanOrEqual(1);++ const secondTurnToolWrites = toolsUpdates.filter(+ (update) => update.assistantId === 'ast-new-1' && update.toolIds.includes('item_3'),+ );+ expect(secondTurnToolWrites.length).toBeGreaterThanOrEqual(1);+ });++ it('should forward cumulative tools_calling chunks for multiple Codex tools in one step', async () => {+ await runWithEvents(+ [+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Running the first checks.'),+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),+ codexCommandStarted('item_2', "/bin/zsh -lc 'git status --short'"),+ codexCommandCompleted('item_2', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),+ codexAgentMessage('item_3', 'Now I will inspect the commit details.'),+ codexCommandStarted('item_4', "/bin/zsh -lc 'git show --stat --summary HEAD'"),+ codexCommandCompleted(+ 'item_4',+ "/bin/zsh -lc 'git show --stat --summary HEAD'",+ ' src/file.ts | 1 +\n',+ ),+ codexTurnCompleted({ input_tokens: 10, output_tokens: 3 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results[0]?.value as ReturnType<+ typeof vi.fn+ >;+ expect(handlerSpy).toBeDefined();++ const toolsCallingChunks = handlerSpy.mock.calls+ .map((call) => call[0])+ .filter(+ (event: any) =>+ event?.type === 'stream_chunk' && event.data?.chunkType === 'tools_calling',+ );++ expect(toolsCallingChunks).toHaveLength(3);+ expect(toolsCallingChunks[0]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([+ 'item_1',+ ]);+ expect(toolsCallingChunks[1]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([+ 'item_1',+ 'item_2',+ ]);+ expect(toolsCallingChunks[2]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([+ 'item_4',+ ]);+ });++ it('should cut new assistants for later agent_message items in the same Codex turn', async () => {+ const idCounter = { assistant: 0, tool: 0 };+ mockCreateMessage.mockImplementation(async (params: any) => {+ if (params.role === 'tool') {+ idCounter.tool += 1;+ return { id: `tool-${idCounter.tool}` };+ }++ if (params.role === 'assistant') {+ idCounter.assistant += 1;+ return { id: `ast-new-${idCounter.assistant}` };+ }++ return { id: `created-${params.role}-${idCounter.assistant + idCounter.tool}` };+ });++ const toolsUpdates: Array<{ assistantId: string; toolIds: string[] }> = [];+ const contentUpdates: Array<{ assistantId: string; content: string }> = [];+ mockUpdateMessage.mockImplementation(async (id: string, val: any) => {+ if (val.tools) {+ toolsUpdates.push({+ assistantId: id,+ toolIds: val.tools.map((tool: any) => tool.id),+ });+ }+ if (typeof val.content === 'string') {+ contentUpdates.push({ assistantId: id, content: val.content });+ }+ });++ await runWithEvents(+ [+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage(+ 'item_0',+ 'Running the five read-only checks from the repo root exactly as requested.',+ ),+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),+ codexCommandStarted('item_2', "/bin/zsh -lc 'git status --short'"),+ codexCommandCompleted('item_2', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),+ codexCommandStarted('item_3', "/bin/zsh -lc 'rg --files src | head -n 5'"),+ codexCommandCompleted(+ 'item_3',+ "/bin/zsh -lc 'rg --files src | head -n 5'",+ 'src/store/session/store.ts\n',+ ),+ codexAgentMessage(+ 'item_4',+ 'The workspace is dirty in a few files, but I am only collecting read-only outputs.',+ ),+ codexCommandStarted(+ 'item_5',+ `/bin/zsh -lc 'rg -n "heterogeneousAgent" src apps packages | head -n 10'`,+ ),+ codexCommandCompleted(+ 'item_5',+ `/bin/zsh -lc 'rg -n "heterogeneousAgent" src apps packages | head -n 10'`,+ 'apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts:18:import ...\n',+ ),+ codexCommandStarted(+ 'item_6',+ `/bin/zsh -lc 'rg -n "tool_call_id|tool_calls" src packages | head -n 10'`,+ ),+ codexCommandCompleted(+ 'item_6',+ `/bin/zsh -lc 'rg -n "tool_call_id|tool_calls" src packages | head -n 10'`,+ 'packages/agent-runtime/src/agents/GeneralChatAgent.ts:34:...\n',+ ),+ codexAgentMessage(+ 'item_7',+ 'Confirmed the repo root and the requested ripgrep checks returned matches.',+ ),+ codexTurnCompleted({+ cached_input_tokens: 92672,+ input_tokens: 107744,+ output_tokens: 996,+ }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const assistantCreates = mockCreateMessage.mock.calls.filter(+ ([params]: any) => params.role === 'assistant',+ );+ expect(assistantCreates).toHaveLength(2);+ expect(assistantCreates[0]?.[0]).toMatchObject({+ parentId: 'tool-3',+ role: 'assistant',+ });+ expect(assistantCreates[1]?.[0]).toMatchObject({+ parentId: 'tool-5',+ role: 'assistant',+ });++ const firstStepToolWrites = toolsUpdates.filter(+ (update) =>+ update.assistantId === 'ast-initial' &&+ update.toolIds.includes('item_1') &&+ update.toolIds.includes('item_2') &&+ update.toolIds.includes('item_3'),+ );+ expect(firstStepToolWrites.length).toBeGreaterThanOrEqual(1);++ const secondStepToolWrites = toolsUpdates.filter(+ (update) =>+ update.assistantId === 'ast-new-1' &&+ update.toolIds.includes('item_5') &&+ update.toolIds.includes('item_6'),+ );+ expect(secondStepToolWrites.length).toBeGreaterThanOrEqual(1);++ const thirdStepToolWrites = toolsUpdates.filter(+ (update) => update.assistantId === 'ast-new-2' && update.toolIds.length > 0,+ );+ expect(thirdStepToolWrites).toHaveLength(0);++ expect(+ contentUpdates.findLast((update) => update.assistantId === 'ast-initial')?.content,+ ).toContain('Running the five read-only checks');+ expect(+ contentUpdates.findLast((update) => update.assistantId === 'ast-new-1')?.content,+ ).toContain('The workspace is dirty in a few files');+ expect(+ contentUpdates.findLast((update) => update.assistantId === 'ast-new-2')?.content,+ ).toContain('Confirmed the repo root');+ });});// ────────────────────────────────────────────────────@@ -1037,7 +1691,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {it('should have no orphan tools when replaying real CC trace', async () => {// Load real trace dataconst fs = await import('node:fs');- const path = await import('node:path');const tracePath = path.join(process.cwd(), 'regression.json');let traceData: any[];@@ -1376,8 +2029,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {const subAssistantMsg = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'assistant' && p.threadId === threadId,);- const subAssistantId = subAssistantMsg?.[0];-const subToolCreate = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_child',);diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex 22e359f710e..41fbc89116a 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -359,7 +359,7 @@ export class ConversationLifecycleActionImpl {// Per-agent heterogeneousProvider config takes priority over the global gateway mode.const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;- if (isDesktop && heterogeneousProvider?.type === 'claude-code') {+ if (isDesktop && heterogeneousProvider) {// Resolve cwd up-front so the new topic is bound to a project at// creation time. Otherwise the row stays NULL until the post-execution// metadata write — which never lands on cancel/error and meanwhile@@ -379,12 +379,15 @@ export class ConversationLifecycleActionImpl {// Persist messages to DB first (same as client mode)let heteroData: SendMessageServerResponse | undefined;try {- const { model } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());heteroData = await aiChatService.sendMessageInServer({agentId: operationContext.agentId,groupId: operationContext.groupId ?? undefined,- newAssistantMessage: { model, provider: 'claude-code' },+ // External CLIs own model selection and may reroute independently+ // from the agent's requested model. Persist only the runtime+ // provider up front; the adapter backfills the actual model later+ // if the CLI reports it.+ newAssistantMessage: { provider: heterogeneousProvider.type },newTopic: !operationContext.topicId? {metadata: workingDirectory ? { workingDirectory } : undefined,diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 0b116c5615a..2c14ecbbd40 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -5,7 +5,8 @@ import type {StreamStartData,ToolExecuteData,} from '@lobechat/agent-gateway-client';-import type { ConversationContext } from '@lobechat/types';+import type { ChatMessageError, ConversationContext } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';import { messageService } from '@/services/message';import type { ChatStore } from '@/store/chat/store';@@ -20,6 +21,29 @@ const fetchAndReplaceMessages = async (get: () => ChatStore, context: Conversatiget().replaceMessages(messages, { context });};+const toChatMessageError = (data: unknown): ChatMessageError => {+ if (typeof data === 'object' && data && 'type' in data && typeof data.type === 'string') {+ const error = data as ChatMessageError;+ return {+ ...error,+ message: error.message || error.body?.message,+ };+ }++ const message =+ typeof data === 'object' && data && 'message' in data && typeof data.message === 'string'+ ? data.message+ : typeof data === 'object' && data && 'error' in data && typeof data.error === 'string'+ ? data.error+ : 'Unknown error';++ return {+ body: { message },+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+};+/*** Creates a handler function that processes Agent Gateway events* and maps them to the chat store's message update actions.@@ -55,6 +79,7 @@ export const createGatewayEventHandler = (// Mutable — switches to new assistant message ID on each stream_startlet currentAssistantMessageId = params.assistantMessageId;+ let terminalState: 'completed' | 'error' | undefined;// Accumulated content from stream chunks (reset on each stream_start)let accumulatedContent = '';@@ -68,6 +93,12 @@ export const createGatewayEventHandler = (};return (event: AgentStreamEvent) => {+ if (terminalState) return;++ if (event.type === 'agent_runtime_end' || event.type === 'error') {+ terminalState = event.type === 'error' ? 'error' : 'completed';+ }+switch (event.type) {case 'stream_start': {enqueue(async () => {@@ -217,14 +248,26 @@ export const createGatewayEventHandler = (case 'error': {enqueue(async () => {- const errorMsg = event.data?.message || event.data?.error || 'Unknown error';+ const messageError = toChatMessageError(event.data);get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);get().completeOperation(operationId);- // Fetch from DB first — the server may have persisted a richer error- // detail into the message already.- await fetchAndReplaceMessages(get, context).catch(console.error);+ const updateResult = await messageService+ .updateMessageError(currentAssistantMessageId, messageError, {+ agentId: context.agentId,+ groupId: context.groupId,+ threadId: context.threadId,+ topicId: context.topicId,+ })+ .catch(console.error);++ if (updateResult?.success && updateResult.messages) {+ get().replaceMessages(updateResult.messages, { context });+ } else {+ // Fallback when the mutation response doesn't include messages.+ await fetchAndReplaceMessages(get, context).catch(console.error);+ }// Then overlay the inline error. This ensures the UI always shows the// error even if the server hasn't persisted it into the message yet@@ -234,7 +277,7 @@ export const createGatewayEventHandler = (id: currentAssistantMessageId,type: 'updateMessage',value: {- error: { body: { message: errorMsg }, type: 'AgentRuntimeError' },+ error: messageError,},},dispatchContext,diff --git a/src/store/chat/slices/aiChat/actions/heteroResume.ts b/src/store/chat/slices/aiChat/actions/heteroResume.tsindex b1f728162ef..69c815812bb 100644--- a/src/store/chat/slices/aiChat/actions/heteroResume.ts+++ b/src/store/chat/slices/aiChat/actions/heteroResume.ts@@ -1,8 +1,12 @@import type { ChatTopicMetadata } from '@lobechat/types';+export type HeteroResumeBlockedReason = 'cwd_changed' | 'missing_bound_cwd';+export interface HeteroResumeDecision {/** True when a saved cwd exists and disagrees with the current cwd. */cwdChanged: boolean;+ /** Why a saved session could not be resumed safely. */+ reason?: HeteroResumeBlockedReason;/** Session id to resume with, or undefined when resume must be skipped. */resumeSessionId: string | undefined;}@@ -27,11 +31,31 @@ export const resolveHeteroResume = (const savedCwd = metadata?.workingDirectory;const cwd = currentWorkingDirectory ?? '';- const canResume = !!savedSessionId && savedCwd !== undefined && savedCwd === cwd;- const cwdChanged = !!savedSessionId && !canResume;+ if (!savedSessionId) {+ return {+ cwdChanged: false,+ resumeSessionId: undefined,+ };+ }++ if (savedCwd === undefined) {+ return {+ cwdChanged: true,+ reason: 'missing_bound_cwd',+ resumeSessionId: undefined,+ };+ }++ if (savedCwd !== cwd) {+ return {+ cwdChanged: true,+ reason: 'cwd_changed',+ resumeSessionId: undefined,+ };+ }return {- cwdChanged,- resumeSessionId: canResume ? savedSessionId : undefined,+ cwdChanged: false,+ resumeSessionId: savedSessionId,};};diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex b762453e9d3..c6ec4fa859b 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -1,5 +1,11 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { isDesktop } from '@lobechat/const';+import {+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ CODEX_CLI_INSTALL_DOCS_URL,+ type HeterogeneousAgentSessionError,+ HeterogeneousAgentSessionErrorCode,+} from '@lobechat/electron-client-ipc';import type {HeterogeneousAgentEvent,SubagentEventContext,@@ -7,16 +13,18 @@ import type {} from '@lobechat/heterogeneous-agents';import { createAdapter } from '@lobechat/heterogeneous-agents';import type {+ ChatMessageError,ChatToolPayload,ConversationContext,HeterogeneousProviderConfig,MessageMapScope,UIChatMessage,} from '@lobechat/types';-import { ThreadStatus, ThreadType } from '@lobechat/types';+import { AgentRuntimeErrorType, ThreadStatus, ThreadType } from '@lobechat/types';import { createNanoId } from '@lobechat/utils';import { t } from 'i18next';+import { message as antdMessage } from '@/components/AntdStaticMethods';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { messageService } from '@/services/message';import { threadService } from '@/services/thread';@@ -46,6 +54,127 @@ const notifyCompletion = async (title: string, body: string) => {}};+const CLI_AUTH_REQUIRED_PATTERNS = [+ /failed to authenticate/i,+ /invalid authentication credentials/i,+ /authentication[_ ]error/i,+ /not authenticated/i,+ /\bunauthorized\b/i,+ /\b401\b/,+] as const;++const buildCliAuthRequiredSessionError = (+ agentType: 'claude-code' | 'codex',+ rawMessage: string,+): HeterogeneousAgentSessionError => ({+ agentType,+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ docsUrl:+ agentType === 'claude-code' ? CLAUDE_CODE_CLI_INSTALL_DOCS_URL : CODEX_CLI_INSTALL_DOCS_URL,+ message:+ agentType === 'claude-code'+ ? 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.'+ : 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr: rawMessage,+});++const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();++const maybeClassifyCliAuthRequiredError = (+ error: unknown,+ agentType?: string,+): HeterogeneousAgentSessionError | undefined => {+ if (agentType !== 'claude-code' && agentType !== 'codex') return;++ const message =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : typeof error === 'object' &&+ error &&+ 'message' in error &&+ typeof error.message === 'string'+ ? error.message+ : undefined;++ if (!message || !CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(message))) return;++ return buildCliAuthRequiredSessionError(agentType, message);+};++const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageError): boolean => {+ const errorBody = error.body as+ | (HeterogeneousAgentSessionError & { clearEchoedContent?: boolean })+ | undefined;+ if (+ !errorBody?.clearEchoedContent &&+ errorBody?.code !== HeterogeneousAgentSessionErrorCode.AuthRequired+ ) {+ return false;+ }++ const normalizedContent = normalizeErrorText(content);+ const normalizedRawError = normalizeErrorText(+ errorBody?.stderr || errorBody?.message || error.message,+ );++ return !!normalizedContent && !!normalizedRawError && normalizedContent === normalizedRawError;+};++const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError => {+ const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);+ if (authRequiredError) {+ return {+ body: authRequiredError,+ message: authRequiredError.message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }++ if (+ typeof error === 'object' &&+ error &&+ 'message' in error &&+ typeof error.message === 'string' &&+ ('agentType' in error || 'code' in error || 'docsUrl' in error || 'installCommands' in error)+ ) {+ return {+ body: error as HeterogeneousAgentSessionError,+ message: error.message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }++ const message =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : 'Agent execution failed';++ return {+ body: { message },+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+};++const isRecoverableResumeError = (+ error: unknown,+): error is HeterogeneousAgentSessionError & {+ code:+ | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch+ | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound;+} => {+ if (!error || typeof error !== 'object' || !('code' in error)) return false;++ return (+ error.code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch ||+ error.code === HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound+ );+};+export interface HeterogeneousAgentExecutorParams {assistantMessageId: string;context: ConversationContext;@@ -63,6 +192,7 @@ export interface HeterogeneousAgentExecutorParams {* Map heterogeneousProvider.command to adapter type key.*/const resolveAdapterType = (config: HeterogeneousProviderConfig): string => {+ if (config.type) return config.type;// Explicit adapterType in config takes priorityif ((config as any).adapterType) return (config as any).adapterType;@@ -94,7 +224,7 @@ const subscribeBroadcasts = (sessionId: string,callbacks: {onComplete: () => void;- onError: (error: string) => void;+ onError: (error: HeterogeneousAgentSessionError | string) => void;onRawLine: (line: any) => void;},): (() => void) => {@@ -108,7 +238,10 @@ const subscribeBroadcasts = (const onComplete = (_e: any, data: { sessionId: string }) => {if (data.sessionId === sessionId) callbacks.onComplete();};- const onError = (_e: any, data: { error: string; sessionId: string }) => {+ const onError = (+ _e: any,+ data: { error: HeterogeneousAgentSessionError | string; sessionId: string },+ ) => {if (data.sessionId === sessionId) callbacks.onError(data.error);};@@ -915,10 +1048,59 @@ export const executeHeterogeneousAgent = async (context,operationId,});+ const persistTerminalError = async (+ messageError: ChatMessageError,+ options?: { clearContent?: boolean },+ ) => {+ get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);+ get().completeOperation(operationId);++ if (options?.clearContent) {+ await messageService+ .updateMessage(+ currentAssistantMessageId,+ { content: '' },+ {+ agentId: context.agentId,+ topicId: context.topicId,+ },+ )+ .catch(console.error);+ }++ const updateResult = await messageService+ .updateMessageError(currentAssistantMessageId, messageError, {+ agentId: context.agentId,+ groupId: context.groupId,+ threadId: context.threadId,+ topicId: context.topicId,+ })+ .catch(console.error);++ if (updateResult?.success && updateResult.messages) {+ get().replaceMessages(updateResult.messages, { context });+ } else {+ await get().refreshMessages().catch(console.error);+ }++ get().internal_dispatchMessage(+ {+ id: currentAssistantMessageId,+ type: 'updateMessage',+ value: {+ ...(options?.clearContent ? { content: '' } : {}),+ error: messageError,+ },+ },+ { operationId },+ );+ };let agentSessionId: string | undefined;let unsubscribe: (() => void) | undefined;let completed = false;+ let fallbackPromise: Promise<void> | undefined;+ let resumeFallbackTriggered = false;// Track state for DB persistence (main-agent scope)const toolState: ToolPersistenceState = {@@ -976,6 +1158,41 @@ export const executeHeterogeneousAgent = async (// (cleaned up already) or missing in a test stub, treat as not-aborted.const abortSignal = get().operations?.[operationId]?.abortController?.signal;const isAborted = () => !!abortSignal?.aborted;+ const updateTopicMetadata = get().updateTopicMetadata;+ const hasStreamedState = () =>+ !!accumulatedContent ||+ !!accumulatedReasoning ||+ toolState.payloads.length > 0 ||+ toolMsgIdByCallId.size > 0 ||+ subagentRuns.size > 0;+ const clearStaleResumeMetadata = async () => {+ if (!context.topicId || !updateTopicMetadata) return;++ await updateTopicMetadata(context.topicId, {+ heteroSessionId: undefined,+ workingDirectory: workingDirectory ?? '',+ });+ };+ const retryWithoutResume = (error: unknown): boolean => {+ if (+ resumeFallbackTriggered ||+ !resumeSessionId ||+ !isRecoverableResumeError(error) ||+ hasStreamedState()+ ) {+ return false;+ }++ resumeFallbackTriggered = true;+ completed = true;+ fallbackPromise = (async () => {+ await clearStaleResumeMetadata().catch(console.error);+ antdMessage?.info?.(t('heteroAgent.resumeReset.resumeFailed', { ns: 'chat' }));+ await executeHeterogeneousAgent(get, { ...params, resumeSessionId: undefined });+ })();++ return true;+ };/*** Invoked by `ensureSubagentRun` once per lazy Thread creation so the@@ -1068,7 +1285,7 @@ export const executeHeterogeneousAgent = async (const result = await heterogeneousAgentService.startSession({agentType: adapterType,args: heterogeneousProvider.args,- command: heterogeneousProvider.command || 'claude',+ command: heterogeneousProvider.command || (adapterType === 'codex' ? 'codex' : 'claude'),cwd: workingDirectory,env: heterogeneousProvider.env,resumeSessionId,@@ -1454,8 +1671,17 @@ export const executeHeterogeneousAgent = async (// Persist final content + reasoning + model for the last step BEFORE the// terminal event triggers fetchAndReplaceMessages. Usage for this step// was already written per-turn via the turn_metadata branch.+ const terminalMessageError =+ deferredTerminalEvent?.type === 'error'+ ? toHeterogeneousAgentMessageError(deferredTerminalEvent.data, adapterType)+ : undefined;+ const shouldClearTerminalErrorContent =+ !!terminalMessageError &&+ shouldSuppressTerminalErrorEcho(accumulatedContent, terminalMessageError);const updateValue: Record<string, any> = {};- if (accumulatedContent) updateValue.content = accumulatedContent;+ if (accumulatedContent && !shouldClearTerminalErrorContent) {+ updateValue.content = accumulatedContent;+ }if (accumulatedReasoning) updateValue.reasoning = { content: accumulatedReasoning };if (lastModel) updateValue.model = lastModel;if (lastProvider) updateValue.provider = lastProvider;@@ -1469,15 +1695,21 @@ export const executeHeterogeneousAgent = async (.catch(console.error);}- // NOW forward the deferred terminal event — handler will fetchAndReplaceMessages- // and pick up the final persisted state.- const terminal = deferredTerminalEvent ?? {- data: {},- stepIndex: 0,- timestamp: Date.now(),- type: 'agent_runtime_end' as const,- };- eventHandler(toStreamEvent(terminal, operationId));+ if (terminalMessageError) {+ await persistTerminalError(terminalMessageError, {+ clearContent: shouldClearTerminalErrorContent,+ });+ } else {+ // NOW forward the deferred terminal event — handler will fetchAndReplaceMessages+ // and pick up the final persisted state.+ const terminal = deferredTerminalEvent ?? {+ data: {},+ stepIndex: 0,+ timestamp: Date.now(),+ type: 'agent_runtime_end' as const,+ };+ eventHandler(toStreamEvent(terminal, operationId));+ }// Signal completion to the user — dock badge + (window-hidden) notification.// Skip for aborted runs and for error terminations.@@ -1491,11 +1723,23 @@ export const executeHeterogeneousAgent = async (onError: async (error) => {if (completed) return;+ if (retryWithoutResume(error)) return;completed = true;await persistQueue.catch(console.error);- if (accumulatedContent) {+ const deferredMessageError =+ deferredTerminalEvent?.type === 'error'+ ? toHeterogeneousAgentMessageError(deferredTerminalEvent.data, adapterType)+ : undefined;+ const messageError =+ deferredMessageError || toHeterogeneousAgentMessageError(error, adapterType);+ const shouldClearTerminalErrorContent = shouldSuppressTerminalErrorEcho(+ accumulatedContent,+ messageError,+ );++ if (accumulatedContent && !shouldClearTerminalErrorContent) {await messageService.updateMessage(currentAssistantMessageId,@@ -1513,17 +1757,7 @@ export const executeHeterogeneousAgent = async (// already marked cancelled and the partial content is persisted above.if (isAborted()) return;- eventHandler(- toStreamEvent(- {- data: { error, message: error },- stepIndex: 0,- timestamp: Date.now(),- type: 'error',- },- operationId,- ),- );+ await persistTerminalError(messageError, { clearContent: shouldClearTerminalErrorContent });},});@@ -1537,33 +1771,33 @@ export const executeHeterogeneousAgent = async (// topic-level binding — pinning the topic to this cwd once the agent has// executed here.if (adapter.sessionId && context.topicId) {- get().updateTopicMetadata(context.topicId, {+ await updateTopicMetadata?.(context.topicId, {heteroSessionId: adapter.sessionId,workingDirectory: workingDirectory ?? '',});}} catch (error) {if (!completed) {+ if (retryWithoutResume(error)) {+ await fallbackPromise;+ return;+ }completed = true;// `sendPrompt` rejects when the CLI exits non-zero, which is how SIGINT// lands here too. If the user cancelled, don't surface an error.if (isAborted()) return;- const errorMsg = error instanceof Error ? error.message : 'Agent execution failed';- eventHandler(- toStreamEvent(- {- data: { error: errorMsg, message: errorMsg },- stepIndex: 0,- timestamp: Date.now(),- type: 'error',- },- operationId,- ),- );+ const messageError = toHeterogeneousAgentMessageError(error, adapterType);+ await persistTerminalError(messageError, {+ clearContent: shouldSuppressTerminalErrorEcho(accumulatedContent, messageError),+ });}} finally {unsubscribe?.();// Don't stopSession here — keep it alive for multi-turn resume.// Session cleanup happens on topic deletion or Electron quit.}++ if (fallbackPromise) {+ await fallbackPromise;+ }};