π€― 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(hetero): align tool_end payload+result so onAfterCall works for CLI agents (#16809)
Arvin Xuec18d0a5a23e
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex e115b6e0ee1..b9a618f9e31 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -445,6 +445,47 @@ describe('ClaudeCodeAdapter', () => {expect(end!.data.toolCallId).toBe('t1');});+ it('aligns tool_end with the server shape β carries payload + result', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ id: 'msg_1',+ content: [+ {+ id: 't1',+ input: { command: 'git worktree add ../wt' },+ name: 'Bash',+ type: 'tool_use',+ },+ ],+ },+ type: 'assistant',+ });++ const events = adapter.adapt({+ message: {+ content: [{ content: 'Preparing worktree', tool_use_id: 't1', type: 'tool_result' }],+ role: 'user',+ },+ type: 'user',+ });++ const end = events.find((e) => e.type === 'tool_end');+ // Payload mirrors tool_start's `{ toolCalling }` so `onAfterCall` can resolve+ // the executor by identifier and read the command args; result gives success.+ expect(end!.data.payload).toEqual({+ toolCalling: {+ apiName: 'Bash',+ arguments: JSON.stringify({ command: 'git worktree add ../wt' }),+ id: 't1',+ identifier: 'claude-code',+ type: 'default',+ },+ });+ expect(end!.data.result).toMatchObject({ content: 'Preparing worktree', success: true });+ });+it('handles array-shaped tool_result content', () => {const adapter = new ClaudeCodeAdapter();adapter.adapt({ subtype: 'init', type: 'system' });@@ -1714,6 +1755,10 @@ describe('ClaudeCodeAdapter', () => {expect(events).toHaveLength(1);expect(events[0].type).toBe('tool_end');expect(events[0].data.toolCallId).toBe('t1');+ // A pending tool that never produced a result must NOT report success β+ // otherwise side-effect hooks would treat an unfinished tool as completed.+ expect(events[0].data.isSuccess).toBe(false);+ expect(events[0].data.result).toMatchObject({ success: false });});it('returns empty array when no pending tools', () => {diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 7b755cbdfd6..30fda4d1683 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -557,6 +557,13 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {* `SubagentSpawnMetadata`.*/private mainToolInputsById = new Map<string, Record<string, any>>();+ /**+ * `tool_use.id β ToolCallPayload`, so `tool_end` can re-attach the same+ * `{ toolCalling }` payload the server ships β aligning the hetero event+ * stream with the gateway/server one so renderer `onAfterCall` hooks fire+ * identically regardless of runtime.+ */+ private toolPayloadById = new Map<string, ToolCallPayload>();/*** Set of parent tool_use ids whose spawn metadata has already been* announced on a subagent event. Guarantees `spawnMetadata` appears@@ -676,9 +683,12 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {}flush(): HeterogeneousAgentEvent[] {- // Close any still-open tools (shouldn't happen in normal flow, but be safe)+ // A still-pending tool never produced a result (the CLI ended / was cancelled+ // mid-tool), so mark it UNSUCCESSFUL β mirrors Codex's drain and stops a+ // side-effect hook (e.g. worktree detection) from treating an unfinished+ // `git worktree add` as a success.const events = [...this.pendingToolCalls].map((id) =>- this.makeEvent('tool_end', { isSuccess: true, toolCallId: id }),+ this.makeEvent('tool_end', this.buildToolEndData(id, false)),);this.pendingToolCalls.clear();return events;@@ -816,14 +826,19 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {// domain-named) instead of the wire-prefixed MCP form. Identifier// stays `claude-code` because this remains a CC-side tool.const apiName = block.name === ASK_USER_MCP_TOOL_NAME ? ASK_USER_API_NAME : block.name;- newToolCalls.push({+ const toolPayload: ToolCallPayload = {apiName,arguments: JSON.stringify(block.input || {}),id: block.id,identifier: 'claude-code',type: 'default',- });+ };+ newToolCalls.push(toolPayload);this.pendingToolCalls.add(block.id);+ // Cache the payload by id so `tool_end` can carry the same+ // `{ toolCalling }` the server emits β keeps the event stream aligned+ // so renderer `onAfterCall` hooks fire identically across runtimes.+ this.toolPayloadById.set(block.id, toolPayload);// Cache EVERY main-agent tool_use input so the subagent-spawn// handler (`emitToolChunk`) can look up the parent's args on// first subagent event regardless of which spawn-tool name CC@@ -1017,14 +1032,19 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {// domain-named) instead of the wire-prefixed MCP form. Identifier// stays `claude-code` because this remains a CC-side tool.const apiName = block.name === ASK_USER_MCP_TOOL_NAME ? ASK_USER_API_NAME : block.name;- newToolCalls.push({+ const toolPayload: ToolCallPayload = {apiName,arguments: JSON.stringify(block.input || {}),id: block.id,identifier: 'claude-code',type: 'default',- });+ };+ newToolCalls.push(toolPayload);this.pendingToolCalls.add(block.id);+ // Cache the payload by id so `tool_end` can carry the same+ // `{ toolCalling }` the server emits β keeps the event stream aligned+ // so renderer `onAfterCall` hooks fire identically across runtimes.+ this.toolPayloadById.set(block.id, toolPayload);if (block.name === CC_TODO_WRITE_TOOL_NAME && block.input) {this.todoWriteInputs.set(block.id, block.input as TodoWriteArgs);}@@ -1134,6 +1154,33 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {return events;}+ /**+ * Build `tool_end` event data aligned with the server/gateway shape: alongside+ * `{ isSuccess, toolCallId }`, re-attach the tool's `{ toolCalling }` payload+ * (from `toolPayloadById`) and a `result` mirroring a `BuiltinToolResult`. This+ * is what lets the renderer's `onAfterCall` dispatch resolve the executor (by+ * `identifier`) and observe the result β otherwise hetero tool_end carried no+ * payload/result and `onAfterCall` was a silent no-op for CLI runs.+ */+ private buildToolEndData(+ toolCallId: string,+ isSuccess: boolean,+ opts?: { content?: string; state?: unknown; subagent?: SubagentEventContext },+ ): Record<string, any> {+ const data: Record<string, any> = { isSuccess, toolCallId };+ if (opts?.subagent) data.subagent = opts.subagent;++ const toolCalling = this.toolPayloadById.get(toolCallId);+ if (toolCalling) data.payload = { toolCalling };++ data.result = {+ content: opts?.content ?? '',+ success: isSuccess,+ ...(opts?.state ? { state: opts.state } : {}),+ };+ return data;+ }+/*** Handle user events β these contain tool_result blocks.* NOTE: In Claude Code, tool results are emitted as `type: 'user'` events@@ -1256,11 +1303,14 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {if (this.pendingToolCalls.has(toolCallId)) {this.pendingToolCalls.delete(toolCallId);events.push(- this.makeEvent('tool_end', {- isSuccess: !block.is_error,- subagent: subagentCtx,- toolCallId,- }),+ this.makeEvent(+ 'tool_end',+ this.buildToolEndData(toolCallId, !block.is_error, {+ content: resultContent,+ state: pluginState,+ subagent: subagentCtx,+ }),+ ),);}}diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.tsindex 133025c62aa..b3cad360133 100644--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts@@ -427,6 +427,36 @@ describe('CodexAdapter', () => {});});+ it('aligns tool_end with the server shape β carries payload + result', () => {+ const adapter = new CodexAdapter();+ adapter.adapt({+ item: {+ command: 'git worktree add /wt',+ id: 'item_1',+ status: 'in_progress',+ type: 'command_execution',+ },+ type: 'item.started',+ });+ const completed = adapter.adapt({+ item: {+ aggregated_output: 'Preparing worktree',+ command: 'git worktree add /wt',+ exit_code: 0,+ id: 'item_1',+ status: 'completed',+ type: 'command_execution',+ },+ type: 'item.completed',+ });++ const end = completed.find((e) => e.type === 'tool_end');+ expect(end!.data.payload).toMatchObject({+ toolCalling: { apiName: 'command_execution', id: 'item_1', identifier: 'codex' },+ });+ expect(end!.data.result).toMatchObject({ success: true });+ });+it('maps command execution items into tool lifecycle events', () => {const adapter = new CodexAdapter();diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.tsindex 30952cb7a2f..88dfd3e8555 100644--- a/packages/heterogeneous-agents/src/adapters/codex.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.ts@@ -996,19 +996,30 @@ export class CodexAdapter implements AgentEventAdapter {const belongsToCurrentStep =pendingStepIndex === undefined || pendingStepIndex === this.stepIndex;+ const toolPayload = toToolPayload(item);if (!this.pendingToolCalls.has(item.id)) {- const tool = toToolPayload(item);- this.pendingToolCallStepIndex.set(tool.id, this.stepIndex);- events.push(...this.emitToolChunk(tool));+ this.pendingToolCallStepIndex.set(toolPayload.id, this.stepIndex);+ events.push(...this.emitToolChunk(toolPayload));}this.pendingToolCalls.delete(item.id);this.pendingToolCallStepIndex.delete(item.id);if (belongsToCurrentStep) this.hasToolActivitySinceAgentMessage = true;- events.push(this.makeEvent('tool_result', getToolResultData(item as CodexToolItem)));+ const resultData = getToolResultData(item as CodexToolItem);+ const isSuccess = isSuccessfulToolCompletion(item as CodexToolItem);+ events.push(this.makeEvent('tool_result', resultData));+ // Align tool_end with the server/gateway shape β carry the `{ toolCalling }`+ // payload + a `BuiltinToolResult`-shaped `result` so renderer `onAfterCall`+ // hooks resolve the executor and observe the result, identically to server runs.events.push(this.makeEvent('tool_end', {- isSuccess: isSuccessfulToolCompletion(item as CodexToolItem),+ isSuccess,+ payload: { toolCalling: toolPayload },+ result: {+ content: resultData.content,+ success: isSuccess,+ ...(resultData.pluginState ? { state: resultData.pluginState } : {}),+ },toolCallId: item.id,}),);diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 050cfef75f7..5a88a074cfa 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -934,6 +934,14 @@ export interface ToolHookContext {* Useful for correlating before/after hooks against the same call.*/toolCallId?: string;+ /**+ * Topic id of the run this tool call belongs to (the bound operation's topic),+ * threaded from the event handler's conversation context. Prefer this over the+ * globally-active topic so a hook's side effects land on the run's own topic+ * even if the user has navigated away mid-run. Undefined when the run has no+ * topic yet.+ */+ topicId?: string;}export interface ToolBeforeCallContext extends ToolHookContext {}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.tsindex 65baee22a88..926bd2aa04a 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts@@ -680,6 +680,7 @@ describe('createGatewayEventHandler', () => {params: { identifier: 'T-3' },result: { content: 'Task deleted', success: true },toolCallId: 'tc-1',+ topicId: 'topic-1',});});@@ -750,6 +751,7 @@ describe('createGatewayEventHandler', () => {identifier: 'lobe-task',params: { identifier: 'T-5', name: 'renamed' },toolCallId: 'tc-3',+ topicId: 'topic-1',});});});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex cafb445f716..de82eec0b43 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -106,7 +106,10 @@ const readToolPayload = (* tool packages can react before their own mutations dispatch (e.g.* optimistic UI). Fires for both client- and server-runtime tools.*/-const dispatchOnBeforeCall = async (data: ToolStartData | undefined): Promise<void> => {+const dispatchOnBeforeCall = async (+ data: ToolStartData | undefined,+ topicId?: string,+): Promise<void> => {const payload = data?.toolCalling as ChatToolPayloadLike | undefined;const identity = readToolPayload(payload);if (!identity) return;@@ -115,7 +118,7 @@ const dispatchOnBeforeCall = async (data: ToolStartData | undefined): Promise<voconst executor = getExecutor(identity.identifier);if (!executor?.onBeforeCall) return;- await executor.onBeforeCall(identity);+ await executor.onBeforeCall({ ...identity, topicId });};/**@@ -140,7 +143,10 @@ const unwrapToolPayload = (raw: unknown): ChatToolPayloadLike | undefined => {* tool packages can react to their own mutations (e.g. invalidate store* caches) regardless of whether the tool ran client- or server-side.*/-const dispatchOnAfterCall = async (data: ToolEndData | undefined): Promise<void> => {+const dispatchOnAfterCall = async (+ data: ToolEndData | undefined,+ topicId?: string,+): Promise<void> => {const identity = readToolPayload(unwrapToolPayload(data?.payload));if (!identity) return;@@ -151,6 +157,7 @@ const dispatchOnAfterCall = async (data: ToolEndData | undefined): Promise<void>await executor.onAfterCall({...identity,result: (data?.result ?? {}) as BuiltinToolResult,+ topicId,});};@@ -598,7 +605,7 @@ export const createGatewayEventHandler = (// Loading is already active from stream_start (not cleared by stream_end).const data = event.data as ToolStartData | undefined;enqueue(async () => {- await dispatchOnBeforeCall(data).catch(console.error);+ await dispatchOnBeforeCall(data, context.topicId ?? undefined).catch(console.error);});break;}@@ -664,7 +671,7 @@ export const createGatewayEventHandler = (enqueue(async () => {await Promise.all([fetchAndReplaceMessages(get, context).catch(console.error),- dispatchOnAfterCall(data).catch(console.error),+ dispatchOnAfterCall(data, context.topicId ?? undefined).catch(console.error),]);});break;diff --git a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.tsnew file mode 100644index 00000000000..8aec36a479d--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { claudeCodeExecutor, codexExecutor } from '../heteroCli';++const detectMocks = vi.hoisted(() => ({ recordWorktreeAdd: vi.fn() }));++vi.mock('../worktreeDetection', () => ({+ recordWorktreeAdd: detectMocks.recordWorktreeAdd,+}));++const call = (over: Record<string, any> = {}) => ({+ apiName: 'Bash',+ identifier: 'claude-code',+ params: { command: 'git worktree add /wt' },+ result: { content: '', success: true },+ topicId: 't1',+ ...over,+});++beforeEach(() => vi.clearAllMocks());++describe('heteroCli executors', () => {+ it('registers the CLI adapter identifiers and exposes no invokable APIs', () => {+ expect(claudeCodeExecutor.identifier).toBe('claude-code');+ expect(codexExecutor.identifier).toBe('codex');+ // Empty apiEnum β never treated as an invokable client tool.+ expect(claudeCodeExecutor.hasApi('Bash')).toBe(false);+ expect(claudeCodeExecutor.getApiNames()).toEqual([]);+ });++ it('records the worktree for a successful shell call, keyed by the run topic', async () => {+ await claudeCodeExecutor.onAfterCall!(call());+ expect(detectMocks.recordWorktreeAdd).toHaveBeenCalledWith({+ command: 'git worktree add /wt',+ topicId: 't1',+ });+ });++ it('passes an argv-array command through verbatim (boundaries preserved)', async () => {+ await codexExecutor.onAfterCall!(+ call({+ apiName: 'command_execution',+ identifier: 'codex',+ params: { command: ['git', 'worktree', 'add', '/tmp/my wt'] },+ }),+ );+ expect(detectMocks.recordWorktreeAdd).toHaveBeenCalledWith({+ command: ['git', 'worktree', 'add', '/tmp/my wt'],+ topicId: 't1',+ });+ });++ it('skips a failed call', async () => {+ await claudeCodeExecutor.onAfterCall!(call({ result: { content: 'fatal', success: false } }));+ expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ });++ it('skips when there is no run topic', async () => {+ await claudeCodeExecutor.onAfterCall!(call({ topicId: undefined }));+ expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ });++ it('is constrained to the shell tool β ignores other tools', async () => {+ // A non-shell tool (e.g. Write) whose params happen to carry `content`.+ await claudeCodeExecutor.onAfterCall!(+ call({ apiName: 'Write', params: { command: 'git worktree add /wt' } }),+ );+ expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ });++ it('reads only command/cmd, never content', async () => {+ await claudeCodeExecutor.onAfterCall!(+ call({ params: { content: 'git worktree add /wt', file_path: 'a.md' } }),+ );+ expect(detectMocks.recordWorktreeAdd).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.tsnew file mode 100644index 00000000000..84f386f7a34--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { parseWorktreeAddPath, recordWorktreeAdd } from '../worktreeDetection';++const chatMocks = vi.hoisted(() => ({+ topics: {} as Record<string, { metadata?: Record<string, any> }>,+ updateTopicMetadata: vi.fn(),+}));++vi.mock('@/store/chat/store', () => ({+ getChatStoreState: () => chatMocks,+}));++vi.mock('@/store/chat/selectors', () => ({+ topicSelectors: {+ getTopicById: (id: string) => (state: typeof chatMocks) => state.topics[id],+ },+}));++describe('parseWorktreeAddPath', () => {+ it('resolves a relative path against the source cwd', () => {+ expect(parseWorktreeAddPath('git worktree add ../wt', '/repo')).toBe('/wt');+ expect(parseWorktreeAddPath('git worktree add wt', '/repo')).toBe('/repo/wt');+ });++ it('keeps an absolute path as-is', () => {+ expect(parseWorktreeAddPath('git worktree add /tmp/wt', '/repo')).toBe('/tmp/wt');+ });++ it('skips flags and their values', () => {+ expect(parseWorktreeAddPath('git worktree add -b feature ../feat', '/repo')).toBe('/feat');+ expect(parseWorktreeAddPath('git worktree add --detach /tmp/wt', '/repo')).toBe('/tmp/wt');+ });++ it('stops at a shell separator', () => {+ expect(parseWorktreeAddPath('cd /repo && git worktree add wt && cd wt', '/repo')).toBe(+ '/repo/wt',+ );+ });++ it('preserves argv boundaries for the array form β a path with spaces stays intact', () => {+ expect(parseWorktreeAddPath(['git', 'worktree', 'add', '/tmp/my wt'], '/repo')).toBe(+ '/tmp/my wt',+ );+ expect(parseWorktreeAddPath(['git', 'worktree', 'add', 'my wt'], '/repo')).toBe('/repo/my wt');+ });++ it('requires an actual git invocation β not the words in another command', () => {+ expect(parseWorktreeAddPath('echo git worktree add ../wt', '/repo')).toBeUndefined();+ expect(parseWorktreeAddPath('rg "git worktree add" .', '/repo')).toBeUndefined();+ expect(parseWorktreeAddPath('grep -r "worktree add" src', '/repo')).toBeUndefined();+ });++ it('accepts wrappers and git global options', () => {+ expect(parseWorktreeAddPath('sudo git worktree add /wt', '/repo')).toBe('/wt');+ expect(parseWorktreeAddPath('git -C /elsewhere worktree add wt', '/repo')).toBe(+ '/elsewhere/wt',+ );+ expect(parseWorktreeAddPath('git -c core.hooksPath=/x worktree add /wt', '/repo')).toBe('/wt');+ });++ it('returns undefined for non-worktree-add calls', () => {+ expect(parseWorktreeAddPath('git status', '/repo')).toBeUndefined();+ expect(parseWorktreeAddPath('git worktree list', '/repo')).toBeUndefined();+ });+});++const PR_TOPIC = {+ metadata: { workingDirectoryConfig: { path: '/repo', repoType: 'github' } },+};++beforeEach(() => {+ vi.clearAllMocks();+ chatMocks.topics = {};+});++describe('recordWorktreeAdd', () => {+ it('records the new worktree onto the given (run) topic', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordWorktreeAdd({ command: 'git worktree add ../wt', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/wt', isWorktree: true },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('targets the passed topicId, not the active one', async () => {+ chatMocks.topics = { other: PR_TOPIC, t1: PR_TOPIC };++ await recordWorktreeAdd({ command: 'git worktree add /wt', topicId: 'other' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('other', expect.anything());+ });++ it('does nothing when the worktree resolves to the source path', async () => {+ chatMocks.topics = { t1: { metadata: { workingDirectoryConfig: { path: '/repo' } } } };+ await recordWorktreeAdd({ command: 'git worktree add /repo', topicId: 't1' });+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('is idempotent when the active worktree is already set', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree: '/wt', isWorktree: true },+ path: '/repo',+ },+ },+ },+ };+ await recordWorktreeAdd({ command: 'git worktree add /wt', topicId: 't1' });+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('does nothing for a non-worktree command', async () => {+ chatMocks.topics = { t1: PR_TOPIC };+ await recordWorktreeAdd({ command: 'ls -la', topicId: 't1' });+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.tsnew file mode 100644index 00000000000..feb8d69b974--- /dev/null+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts@@ -0,0 +1,70 @@+import type { ToolAfterCallContext } from '@lobechat/types';+import { BaseExecutor } from '@lobechat/types';++import { recordWorktreeAdd } from './worktreeDetection';++/**+ * Hook-only executor for a heterogeneous CLI agent's tool identifier+ * (`claude-code` / `codex` β set by the adapters in+ * `packages/heterogeneous-agents/src/adapters/*`). These agents run their OWN+ * tools, so this executor is NEVER invoked: `apiEnum` is empty β `hasApi()` is+ * always false β the client-tool dispatch (`hasExecutor`) never routes to+ * `invoke`, and no phantom tool is exposed to the model.+ *+ * It exists solely so the `tool_end` dispatcher+ * (`gatewayEventHandler.dispatchOnAfterCall`, which resolves the executor by the+ * tool's `identifier`) can reach `onAfterCall` and observe the CLI's shell tool+ * results renderer-side β the same seam idiomatic builtin tools use to react to+ * their own mutations.+ */+const EMPTY_API_ENUM = {} as Record<string, string>;++/**+ * Pull the command out of a shell tool's parsed params. Only reads `command`/`cmd`+ * β never `content` β so a file-write tool can't be mistaken for a shell command.+ * Returns the raw value (string OR the argv-array form) so the detector can keep+ * argument boundaries.+ */+const readShellCommand = (params: unknown): string | string[] | undefined => {+ if (!params || typeof params !== 'object') return undefined;+ const raw = (params as { cmd?: unknown; command?: unknown }).command ?? (params as any).cmd;+ if (typeof raw === 'string') return raw;+ if (Array.isArray(raw) && raw.every((t) => typeof t === 'string')) return raw as string[];+ return undefined;+};++class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {+ protected readonly apiEnum = EMPTY_API_ENUM;++ /**+ * @param identifier The CLI adapter's tool identifier (`claude-code` / `codex`).+ * @param shellApiNames The adapter's shell / run-command tool api name(s). Side+ * effects are constrained to THIS tool first, then handled uniformly β we don't+ * sniff every tool call's params.+ */+ constructor(+ readonly identifier: string,+ private readonly shellApiNames: ReadonlySet<string>,+ ) {+ super();+ }++ onAfterCall = async ({+ apiName,+ params,+ result,+ topicId,+ }: ToolAfterCallContext): Promise<void> => {+ // Constrain to a SUCCESSFUL run of the shell tool bound to a run topic.+ if (!result.success || !topicId || !this.shellApiNames.has(apiName)) return;++ const command = readShellCommand(params);+ if (command === undefined) return;++ await recordWorktreeAdd({ command, topicId });+ };+}++// CC's shell tool is `Bash`; Codex's is `command_execution`.+export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']));+export const codexExecutor = new HeteroCliExecutor('codex', new Set(['command_execution']));diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex 587e723d958..11d978ac394 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -20,6 +20,7 @@ import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';+import { claudeCodeExecutor, codexExecutor } from './heteroCli';import { activatorExecutor } from './lobe-activator';import { agentDocumentsExecutor } from './lobe-agent-documents';import { messageExecutor } from './lobe-message';@@ -137,6 +138,10 @@ export const registerBuiltinToolExecutors = (): void => {if (executorsRegistered) return;registerExecutors([+ // Hook-only executors for heterogeneous CLI agents (Claude Code / Codex) β+ // observe their shell tool results via `onAfterCall` (never invoked).+ claudeCodeExecutor,+ codexExecutor,agentBuilderExecutor,agentDocumentsExecutor,agentManagementExecutor,diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsnew file mode 100644index 00000000000..d2958dd3ad5--- /dev/null+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -0,0 +1,185 @@+import type { WorkingDirConfig } from '@lobechat/types';+import { getWorkingDirSourcePath } from '@lobechat/types';+import isEqual from 'fast-deep-equal';++import { topicSelectors } from '@/store/chat/selectors';+import { getChatStoreState } from '@/store/chat/store';++/**+ * Detect `git worktree add <path>` in a heterogeneous CLI agent's shell tool call+ * and flip the active topic's working-directory state into that worktree.+ *+ * Runs from the `claude-code` / `codex` executor's `onAfterCall` hook (renderer-side,+ * fired on `tool_end`). Mirrors what `WorktreeSwitcher` writes on a manual selection:+ * only `git.activeWorktree` / `isWorktree` change β the CLI session cwd stays anchored+ * to the source repo (hetero anchors cwd to source; the worktree is a record).+ */++/** Flags on `git worktree add` that consume the following token as their value. */+const VALUE_FLAGS = new Set(['-b', '-B', '--reason']);++const stripQuotes = (token: string): string => {+ if (token.length >= 2) {+ const first = token[0];+ const last = token.at(-1);+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {+ return token.slice(1, -1);+ }+ }+ return token;+};++const isAbsolute = (p: string): boolean =>+ p.startsWith('/') || p.startsWith('~') || /^[A-Z]:[\\/]/i.test(p) || p.startsWith('\\\\');++/** Collapse `.`/`..` segments in a POSIX path without touching the filesystem. */+const normalizePosix = (p: string): string => {+ const isAbs = p.startsWith('/');+ const out: string[] = [];+ for (const part of p.split('/')) {+ if (part === '' || part === '.') continue;+ if (part === '..') {+ if (out.length > 0 && out.at(-1) !== '..') out.pop();+ else if (!isAbs) out.push('..');+ } else {+ out.push(part);+ }+ }+ return (isAbs ? '/' : '') + out.join('/');+};++const resolveWorktreePath = (p: string, cwd?: string): string => {+ // Windows / home-relative paths: can't resolve without the device fs, keep as-is.+ if (isAbsolute(p)) return p.startsWith('/') ? normalizePosix(p) : p;+ if (!cwd) return p;+ return normalizePosix(`${cwd}/${p}`);+};++const tokenize = (s: string): string[] => s.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];++/** `git` global options that consume the following token as their value. */+const GIT_VALUE_OPTS = new Set([+ '-C',+ '-c',+ '--git-dir',+ '--work-tree',+ '--namespace',+ '--super-prefix',+ '--config-env',+]);+/** Command wrappers that may precede the real `git` executable. */+const WRAPPERS = new Set(['sudo', 'env', 'command', 'nice', 'nohup', 'time']);+const isAssignment = (t: string) => /^[A-Z_]\w*=/i.test(t);++/**+ * If ONE command's tokens are a real `git β¦ worktree add <path>` invocation, return+ * the path (resolved against the source cwd, honoring a `-C <dir>` override).+ * Requires the executable to actually be `git` β so `echo git worktree add β¦` or+ * `rg "git worktree add"` never match.+ */+const parseGitWorktreeAddTokens = (tokens: string[], cwd?: string): string | undefined => {+ let i = 0;++ // Strip leading `VAR=val` assignments and command wrappers (sudo/env/β¦).+ while (i < tokens.length && (isAssignment(tokens[i]) || WRAPPERS.has(stripQuotes(tokens[i])))) {+ i += 1;+ }+ if (stripQuotes(tokens[i] ?? '') !== 'git') return undefined;+ i += 1;++ // git global options; `-C <dir>` rebases relative worktree paths.+ let baseCwd = cwd;+ while (i < tokens.length && tokens[i].startsWith('-')) {+ if (tokens[i] === '-C') {+ const dir = stripQuotes(tokens[i + 1] ?? '');+ if (dir) baseCwd = resolveWorktreePath(dir, baseCwd);+ i += 2;+ } else if (GIT_VALUE_OPTS.has(tokens[i])) {+ i += 2;+ } else {+ i += 1; // valueless flag or `--opt=val`+ }+ }++ // Subcommand must be exactly `worktree add`.+ if (stripQuotes(tokens[i] ?? '') !== 'worktree') return undefined;+ i += 1;+ if (stripQuotes(tokens[i] ?? '') !== 'add') return undefined;+ i += 1;++ // First positional after `add` is the worktree path.+ for (; i < tokens.length; i += 1) {+ if (VALUE_FLAGS.has(tokens[i])) {+ i += 1; // skip this flag's value+ continue;+ }+ if (tokens[i].startsWith('-')) continue; // other flags+ const path = stripQuotes(tokens[i]);+ if (path) return resolveWorktreePath(path, baseCwd);+ }+ return undefined;+};++/**+ * Parse a shell command for a real `git worktree add <path>` invocation and return+ * the target worktree path (resolved to absolute against `cwd` when relative).+ *+ * `command` is a raw string (tokenized, split on shell separators) OR the argv+ * array form some CLIs use (Codex) β for the array we DON'T re-join+re-tokenize, so+ * a path token containing spaces (`['git','worktree','add','/tmp/my wt']`) keeps its+ * boundary. Returns `undefined` when the call isn't an actual worktree-add.+ */+export const parseWorktreeAddPath = (+ command: string | string[],+ cwd?: string,+): string | undefined => {+ if (Array.isArray(command)) {+ // Already-tokenized argv β a single command, boundaries preserved.+ return command.every((t) => typeof t === 'string')+ ? parseGitWorktreeAddTokens(command, cwd)+ : undefined;+ }+ if (typeof command !== 'string' || !/\bworktree\s+add\b/.test(command)) return undefined;+ for (const segment of command.split(/[\n;|&]/)) {+ const path = parseGitWorktreeAddTokens(tokenize(segment), cwd);+ if (path) return path;+ }+ return undefined;+};++/**+ * Record a successful `git worktree add` as the run topic's active worktree. Writes+ * to the passed `topicId` (the bound operation's topic β from the `onAfterCall`+ * context), NOT the globally-active topic, so a run whose topic the user has+ * navigated away from still updates its own state. No-op when the worktree resolves+ * to the source path itself or nothing would change.+ */+export const recordWorktreeAdd = async (params: {+ command: string | string[];+ topicId: string;+}): Promise<void> => {+ const { command, topicId } = params;+ const state = getChatStoreState();++ const topic = topicSelectors.getTopicById(topicId)(state);+ const currentConfig = topic?.metadata?.workingDirectoryConfig;+ const source = getWorkingDirSourcePath(currentConfig) ?? topic?.metadata?.workingDirectory;++ const worktreePath = parseWorktreeAddPath(command, source);+ if (!worktreePath || !source || worktreePath === source) return;++ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ activeWorktree: worktreePath,+ isWorktree: true,+ };+ const nextConfig: WorkingDirConfig = {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };++ if (isEqual(currentConfig, nextConfig)) return;+ await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });+};