Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(claude-code): add EnterWorktree / ExitWorktree inspectors (#16956)

Arvin Xu1bfc1335c0b4
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 2e2f3c78be3..da4efa90d34 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -147,6 +147,23 @@
"builtins.lobe-claude-code.todoWrite.allDone": "All tasks completed",
"builtins.lobe-claude-code.todoWrite.currentStep": "Current step",
"builtins.lobe-claude-code.todoWrite.todos": "Todos",
+ "builtins.lobe-claude-code.worktree.create.completed": "Worktree created",
+ "builtins.lobe-claude-code.worktree.create.failed": "Failed to create worktree",
+ "builtins.lobe-claude-code.worktree.create.idle": "Create worktree",
+ "builtins.lobe-claude-code.worktree.create.loading": "Creating worktree",
+ "builtins.lobe-claude-code.worktree.discardChanges": "Discard changes",
+ "builtins.lobe-claude-code.worktree.enter.completed": "Entered worktree",
+ "builtins.lobe-claude-code.worktree.enter.failed": "Failed to enter worktree",
+ "builtins.lobe-claude-code.worktree.enter.idle": "Enter worktree",
+ "builtins.lobe-claude-code.worktree.enter.loading": "Entering worktree",
+ "builtins.lobe-claude-code.worktree.exit.completed": "Left worktree",
+ "builtins.lobe-claude-code.worktree.exit.failed": "Failed to leave worktree",
+ "builtins.lobe-claude-code.worktree.exit.idle": "Leave worktree",
+ "builtins.lobe-claude-code.worktree.exit.loading": "Leaving worktree",
+ "builtins.lobe-claude-code.worktree.remove.completed": "Worktree removed",
+ "builtins.lobe-claude-code.worktree.remove.failed": "Failed to remove worktree",
+ "builtins.lobe-claude-code.worktree.remove.idle": "Remove worktree",
+ "builtins.lobe-claude-code.worktree.remove.loading": "Removing worktree",
"builtins.lobe-cloud-sandbox.apiName.editFile": "Edit file",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "Edit file",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "Execute code",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 81e8971070e..0adb853b7aa 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -147,6 +147,23 @@
"builtins.lobe-claude-code.todoWrite.allDone": "全部任务已完成",
"builtins.lobe-claude-code.todoWrite.currentStep": "当前步骤",
"builtins.lobe-claude-code.todoWrite.todos": "待办",
+ "builtins.lobe-claude-code.worktree.create.completed": "已创建工作树",
+ "builtins.lobe-claude-code.worktree.create.failed": "创建工作树失败",
+ "builtins.lobe-claude-code.worktree.create.idle": "创建工作树",
+ "builtins.lobe-claude-code.worktree.create.loading": "正在创建工作树",
+ "builtins.lobe-claude-code.worktree.discardChanges": "丢弃更改",
+ "builtins.lobe-claude-code.worktree.enter.completed": "已进入工作树",
+ "builtins.lobe-claude-code.worktree.enter.failed": "进入工作树失败",
+ "builtins.lobe-claude-code.worktree.enter.idle": "进入工作树",
+ "builtins.lobe-claude-code.worktree.enter.loading": "正在进入工作树",
+ "builtins.lobe-claude-code.worktree.exit.completed": "已退出工作树",
+ "builtins.lobe-claude-code.worktree.exit.failed": "退出工作树失败",
+ "builtins.lobe-claude-code.worktree.exit.idle": "退出工作树",
+ "builtins.lobe-claude-code.worktree.exit.loading": "正在退出工作树",
+ "builtins.lobe-claude-code.worktree.remove.completed": "已删除工作树",
+ "builtins.lobe-claude-code.worktree.remove.failed": "删除工作树失败",
+ "builtins.lobe-claude-code.worktree.remove.idle": "删除工作树",
+ "builtins.lobe-claude-code.worktree.remove.loading": "正在删除工作树",
"builtins.lobe-cloud-sandbox.apiName.editFile": "编辑文件",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "编辑文件",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "执行代码",
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx
new file mode 100644
index 00000000000..7b63474f568
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Worktree.tsx
@@ -0,0 +1,179 @@
+'use client';
+
+import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cx } from 'antd-style';
+import { GitForkIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { EnterWorktreeArgs, ExitWorktreeArgs } from '../../types';
+
+type InspectorPhase = 'completed' | 'failed' | 'idle' | 'loading';
+
+const CREATE_LABEL_KEYS = {
+ completed: 'builtins.lobe-claude-code.worktree.create.completed',
+ failed: 'builtins.lobe-claude-code.worktree.create.failed',
+ idle: 'builtins.lobe-claude-code.worktree.create.idle',
+ loading: 'builtins.lobe-claude-code.worktree.create.loading',
+} as const;
+
+const ENTER_LABEL_KEYS = {
+ completed: 'builtins.lobe-claude-code.worktree.enter.completed',
+ failed: 'builtins.lobe-claude-code.worktree.enter.failed',
+ idle: 'builtins.lobe-claude-code.worktree.enter.idle',
+ loading: 'builtins.lobe-claude-code.worktree.enter.loading',
+} as const;
+
+const EXIT_LABEL_KEYS = {
+ completed: 'builtins.lobe-claude-code.worktree.exit.completed',
+ failed: 'builtins.lobe-claude-code.worktree.exit.failed',
+ idle: 'builtins.lobe-claude-code.worktree.exit.idle',
+ loading: 'builtins.lobe-claude-code.worktree.exit.loading',
+} as const;
+
+const REMOVE_LABEL_KEYS = {
+ completed: 'builtins.lobe-claude-code.worktree.remove.completed',
+ failed: 'builtins.lobe-claude-code.worktree.remove.failed',
+ idle: 'builtins.lobe-claude-code.worktree.remove.idle',
+ loading: 'builtins.lobe-claude-code.worktree.remove.loading',
+} as const;
+
+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: min(420px, 60vw);
+ margin-inline-start: 6px;
+ padding-block: 2px;
+ padding-inline: 10px;
+ border-radius: 999px;
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ icon: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextDescription};
+ `,
+ leadingIcon: css`
+ margin-inline-end: 6px;
+ `,
+ risk: css`
+ flex-shrink: 0;
+
+ margin-inline-start: 6px;
+ padding-block: 1px;
+ padding-inline: 6px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ color: ${cssVar.colorError};
+
+ background: ${cssVar.colorErrorBg};
+ `,
+ target: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+const resolvePhase = (
+ isArgumentsStreaming: boolean | undefined,
+ isLoading: boolean | undefined,
+ hasError: boolean,
+ hasResult: boolean,
+): InspectorPhase => {
+ if (isArgumentsStreaming || isLoading) return 'loading';
+ if (hasError) return 'failed';
+ if (hasResult) return 'completed';
+ return 'idle';
+};
+
+interface WorktreeTargetProps {
+ target: string;
+}
+
+const WorktreeTarget = memo<WorktreeTargetProps>(({ target }) => (
+ <span className={styles.chip} title={target}>
+ <GitForkIcon className={styles.icon} size={12} />
+ <span className={styles.target}>{target}</span>
+ </span>
+));
+
+WorktreeTarget.displayName = 'ClaudeCodeWorktreeTarget';
+
+export const EnterWorktreeInspector = memo<BuiltinInspectorProps<EnterWorktreeArgs>>(
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, result }) => {
+ const { t } = useTranslation('plugin');
+ const name = args?.name?.trim() || partialArgs?.name?.trim();
+ const path = args?.path?.trim() || partialArgs?.path?.trim();
+ const target = name || path;
+ const phase = resolvePhase(
+ isArgumentsStreaming,
+ isLoading,
+ Boolean(result?.error),
+ Boolean(result),
+ );
+ const label = t((path ? ENTER_LABEL_KEYS : CREATE_LABEL_KEYS)[phase]);
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{label}</span>
+ {target && <WorktreeTarget target={target} />}
+ </div>
+ );
+ },
+);
+
+EnterWorktreeInspector.displayName = 'ClaudeCodeEnterWorktreeInspector';
+
+export const ExitWorktreeInspector = memo<BuiltinInspectorProps<ExitWorktreeArgs>>(
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, result }) => {
+ const { t } = useTranslation('plugin');
+ const action = args?.action || partialArgs?.action;
+ const discardChanges = args?.discard_changes ?? partialArgs?.discard_changes;
+ const phase = resolvePhase(
+ isArgumentsStreaming,
+ isLoading,
+ Boolean(result?.error),
+ Boolean(result),
+ );
+ const label = t((action === 'remove' ? REMOVE_LABEL_KEYS : EXIT_LABEL_KEYS)[phase]);
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <GitForkIcon className={cx(styles.icon, styles.leadingIcon)} size={12} />
+ <span>{label}</span>
+ {action === 'remove' && discardChanges && (
+ <span className={styles.risk}>
+ {t('builtins.lobe-claude-code.worktree.discardChanges')}
+ </span>
+ )}
+ </div>
+ );
+ },
+);
+
+ExitWorktreeInspector.displayName = 'ClaudeCodeExitWorktreeInspector';
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
index 9057ceffe57..5629c036183 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts
@@ -25,6 +25,7 @@ import { TodoWriteInspector } from './TodoWrite';
import { ToolSearchInspector } from './ToolSearch';
import { WebFetchInspector } from './WebFetch';
import { WebSearchInspector } from './WebSearch';
+import { EnterWorktreeInspector, ExitWorktreeInspector } from './Worktree';
import { WriteInspector } from './Write';
// CC's own tool names (Bash / Edit / Glob / Grep / Read / Write) are already
@@ -40,6 +41,8 @@ const FixedClaudeCodeInspectors = {
[ClaudeCodeApiName.AskUserQuestion]: AskUserQuestionInspector,
[ClaudeCodeApiName.Bash]: createRunCommandInspector(ClaudeCodeApiName.Bash),
[ClaudeCodeApiName.Edit]: EditInspector,
+ [ClaudeCodeApiName.EnterWorktree]: EnterWorktreeInspector,
+ [ClaudeCodeApiName.ExitWorktree]: ExitWorktreeInspector,
[ClaudeCodeApiName.Glob]: createGlobLocalFilesInspector(ClaudeCodeApiName.Glob),
[ClaudeCodeApiName.Grep]: createGrepContentInspector({
noResultsKey: 'No results',
diff --git a/packages/builtin-tool-claude-code/src/index.ts b/packages/builtin-tool-claude-code/src/index.ts
index 561026f32de..2b79d5520db 100644
--- a/packages/builtin-tool-claude-code/src/index.ts
+++ b/packages/builtin-tool-claude-code/src/index.ts
@@ -7,6 +7,8 @@ export {
ClaudeCodeIdentifier,
type ClaudeCodeTodoItem,
type ClaudeCodeTodoStatus,
+ type EnterWorktreeArgs,
+ type ExitWorktreeArgs,
type ScheduleWakeupArgs,
type SkillArgs,
type TaskOutputArgs,
diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.ts
index f7787b8b0f1..d5a63ebcedc 100644
--- a/packages/builtin-tool-claude-code/src/types.ts
+++ b/packages/builtin-tool-claude-code/src/types.ts
@@ -32,6 +32,10 @@ export enum ClaudeCodeApiName {
AskUserQuestion = 'askUserQuestion',
Bash = 'Bash',
Edit = 'Edit',
+ /** Create a new isolated git worktree or enter an existing one. */
+ EnterWorktree = 'EnterWorktree',
+ /** Leave the worktree created by EnterWorktree, optionally removing it. */
+ ExitWorktree = 'ExitWorktree',
Glob = 'Glob',
Grep = 'Grep',
/**
@@ -109,6 +113,22 @@ export interface SkillArgs {
skill?: string;
}
+/**
+ * Arguments for CC's built-in `EnterWorktree` tool. `name` creates a new
+ * worktree, while `path` switches into one already attached to the repo.
+ * The fields are mutually exclusive; omitting both creates a random name.
+ */
+export interface EnterWorktreeArgs {
+ name?: string;
+ path?: string;
+}
+
+/** Arguments for CC's built-in `ExitWorktree` tool. */
+export interface ExitWorktreeArgs {
+ action: 'keep' | 'remove';
+ discard_changes?: boolean;
+}
+
/**
* Arguments for CC's built-in `Monitor` tool — long-running command monitor.
* CC spawns `command` as a tracked background task; `system task_started`
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 12e93436228..5edacc1a776 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -84,6 +84,23 @@ export default {
'builtins.lobe-claude-code.todoWrite.allDone': 'All tasks completed',
'builtins.lobe-claude-code.todoWrite.currentStep': 'Current step',
'builtins.lobe-claude-code.todoWrite.todos': 'Todos',
+ 'builtins.lobe-claude-code.worktree.create.completed': 'Worktree created',
+ 'builtins.lobe-claude-code.worktree.create.failed': 'Failed to create worktree',
+ 'builtins.lobe-claude-code.worktree.create.idle': 'Create worktree',
+ 'builtins.lobe-claude-code.worktree.create.loading': 'Creating worktree',
+ 'builtins.lobe-claude-code.worktree.discardChanges': 'Discard changes',
+ 'builtins.lobe-claude-code.worktree.enter.completed': 'Entered worktree',
+ 'builtins.lobe-claude-code.worktree.enter.failed': 'Failed to enter worktree',
+ 'builtins.lobe-claude-code.worktree.enter.idle': 'Enter worktree',
+ 'builtins.lobe-claude-code.worktree.enter.loading': 'Entering worktree',
+ 'builtins.lobe-claude-code.worktree.exit.completed': 'Left worktree',
+ 'builtins.lobe-claude-code.worktree.exit.failed': 'Failed to leave worktree',
+ 'builtins.lobe-claude-code.worktree.exit.idle': 'Leave worktree',
+ 'builtins.lobe-claude-code.worktree.exit.loading': 'Leaving worktree',
+ 'builtins.lobe-claude-code.worktree.remove.completed': 'Worktree removed',
+ 'builtins.lobe-claude-code.worktree.remove.failed': 'Failed to remove worktree',
+ 'builtins.lobe-claude-code.worktree.remove.idle': 'Remove worktree',
+ 'builtins.lobe-claude-code.worktree.remove.loading': 'Removing worktree',
'builtins.codex.apiName.collab_tool_call': 'Coordinate subagents',
'builtins.codex.apiName.command_execution': 'Run command',
'builtins.codex.apiName.file_change': 'Edit files',
diff --git a/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts b/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts
index f5175cb73da..a6de46314b7 100644
--- a/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts
+++ b/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts
@@ -39,6 +39,14 @@ export default defineFixtures({
description: 'Patch file contents.',
name: 'Edit',
},
+ {
+ description: 'Create a new git worktree or enter an existing one.',
+ name: 'EnterWorktree',
+ },
+ {
+ description: 'Leave the active Claude Code worktree and optionally remove it.',
+ name: 'ExitWorktree',
+ },
{
description: 'Find files by glob pattern.',
name: 'Glob',
@@ -242,6 +250,44 @@ export default defineFixtures({
old_string: "path: 'tasks',",
},
}),
+ EnterWorktree: variants([
+ {
+ args: { name: 'worktree-icon-in-worktree' },
+ content:
+ 'Created worktree at /workspace/.claude/worktrees/worktree-icon-in-worktree on branch worktree-worktree-icon-in-worktree.',
+ label: 'Create named',
+ },
+ {
+ args: {
+ path: '/workspace/.claude/worktrees/existing-feature-with-a-long-descriptive-name',
+ },
+ content:
+ 'Entered existing worktree at /workspace/.claude/worktrees/existing-feature-with-a-long-descriptive-name.',
+ label: 'Enter existing',
+ },
+ {
+ args: {},
+ content: 'Created worktree with a generated name.',
+ label: 'Create generated',
+ },
+ ]),
+ ExitWorktree: variants([
+ {
+ args: { action: 'keep' },
+ content: 'Left the worktree. The worktree and branch remain on disk.',
+ label: 'Keep on disk',
+ },
+ {
+ args: { action: 'remove' },
+ content: 'Removed the worktree and branch.',
+ label: 'Remove clean',
+ },
+ {
+ args: { action: 'remove', discard_changes: true },
+ content: 'Removed the worktree and discarded 3 files and 1 commit.',
+ label: 'Discard changes',
+ },
+ ]),
Glob: single({
args: { path: 'src/routes', pattern: '**/index.tsx' },
content: 'src/routes/(main)/agent/index.tsx\nsrc/routes/(main)/devtools/index.tsx',
diff --git a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
index b3d562fe50e..45c0cc786a8 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
@@ -2,10 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { claudeCodeExecutor, codexExecutor } from '../heteroCli';
-const detectMocks = vi.hoisted(() => ({ recordGitCommandEffects: vi.fn() }));
+const detectMocks = vi.hoisted(() => ({
+ recordGitCommandEffects: vi.fn(),
+ recordWorktreeEnter: vi.fn(),
+ recordWorktreeExit: vi.fn(),
+}));
vi.mock('../worktreeDetection', () => ({
recordGitCommandEffects: detectMocks.recordGitCommandEffects,
+ recordWorktreeEnter: detectMocks.recordWorktreeEnter,
+ recordWorktreeExit: detectMocks.recordWorktreeExit,
}));
const call = (over: Record<string, any> = {}) => ({
@@ -94,4 +100,59 @@ describe('heteroCli executors', () => {
);
expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
});
+
+ describe("CC's native worktree tools", () => {
+ it('routes EnterWorktree to the enter recorder with the result message', async () => {
+ const content = 'Created worktree at /repo/wt. The session is now working in the worktree.';
+ await claudeCodeExecutor.onAfterCall!(
+ call({
+ apiName: 'EnterWorktree',
+ params: { name: 'wt' },
+ result: { content, success: true },
+ }),
+ );
+
+ expect(detectMocks.recordWorktreeEnter).toHaveBeenCalledWith({ content, topicId: 't1' });
+ // The worktree tools never shell out — no command sniffing.
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('routes ExitWorktree to the exit recorder', async () => {
+ const content = 'Exited and removed worktree at /repo/wt. Session is now back in /repo.';
+ await claudeCodeExecutor.onAfterCall!(
+ call({
+ apiName: 'ExitWorktree',
+ params: { action: 'remove' },
+ result: { content, success: true },
+ }),
+ );
+
+ expect(detectMocks.recordWorktreeExit).toHaveBeenCalledWith({ content, topicId: 't1' });
+ });
+
+ it('does NOT clear the worktree when ExitWorktree was refused', async () => {
+ // CC refuses to remove a dirty worktree — a validation failure, not an exit.
+ await claudeCodeExecutor.onAfterCall!(
+ call({
+ apiName: 'ExitWorktree',
+ params: { action: 'remove' },
+ result: { content: 'Worktree has 3 uncommitted files.', success: false },
+ }),
+ );
+
+ expect(detectMocks.recordWorktreeExit).not.toHaveBeenCalled();
+ });
+
+ it('ignores the worktree tools for Codex, which has none', async () => {
+ await codexExecutor.onAfterCall!(
+ call({
+ apiName: 'EnterWorktree',
+ identifier: 'codex',
+ result: { content: 'Created worktree at /repo/wt. The session is now…', success: true },
+ }),
+ );
+
+ expect(detectMocks.recordWorktreeEnter).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.ts
index e4c3d36485a..6739be08b87 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
@@ -1,9 +1,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ isWorktreeExitContent,
parseWorktreeAddPath,
+ parseWorktreeEnterInfo,
recordGitCommandEffects,
recordWorktreeAdd,
+ recordWorktreeEnter,
+ recordWorktreeExit,
} from '../worktreeDetection';
const chatMocks = vi.hoisted(() => ({
@@ -324,3 +328,205 @@ describe('recordGitCommandEffects', () => {
});
});
});
+
+/**
+ * Verbatim `EnterWorktree` / `ExitWorktree` result messages, matching the templates
+ * Claude Code builds in its `call()`. Only `message` crosses the wire as the
+ * tool_result content, so these strings ARE the contract this module parses.
+ */
+const SESSION_TAIL =
+ 'The session is now working in the worktree. Use ExitWorktree to leave mid-session, or exit the session to be prompted.';
+const enterCreated = (path: string, branch?: string) =>
+ `Created worktree at ${path}${branch ? ` on branch ${branch}` : ''}. ${SESSION_TAIL}`;
+const enterExisting = (path: string) => `Entered worktree at ${path}. ${SESSION_TAIL}`;
+/** A subagent pinned to its own cwd — it moved only itself, never the session. */
+const enterPinnedAgent = (path: string) =>
+ `Entered worktree at ${path} on branch worktree-x. This agent's working directory and write access now point at the worktree; the previous directory was left untouched.`;
+
+describe('parseWorktreeEnterInfo', () => {
+ it('reads path and branch out of a created-worktree message', () => {
+ expect(parseWorktreeEnterInfo(enterCreated('/repo/.claude/worktrees/a', 'worktree-a'))).toEqual(
+ {
+ branch: 'worktree-a',
+ path: '/repo/.claude/worktrees/a',
+ },
+ );
+ });
+
+ it('omits the branch when the message has none', () => {
+ expect(parseWorktreeEnterInfo(enterCreated('/repo/wt'))).toEqual({ path: '/repo/wt' });
+ });
+
+ it('reads the path when switching into an existing worktree', () => {
+ expect(parseWorktreeEnterInfo(enterExisting('/tmp/wt'))).toEqual({ path: '/tmp/wt' });
+ });
+
+ it('keeps a path containing spaces intact', () => {
+ expect(parseWorktreeEnterInfo(enterCreated('/tmp/my wt', 'worktree-b'))?.path).toBe(
+ '/tmp/my wt',
+ );
+ });
+
+ it('ignores a subagent that moved only its own pinned cwd', () => {
+ expect(parseWorktreeEnterInfo(enterPinnedAgent('/tmp/wt'))).toBeUndefined();
+ });
+
+ it('ignores unrelated, truncated or empty content', () => {
+ expect(parseWorktreeEnterInfo('')).toBeUndefined();
+ expect(parseWorktreeEnterInfo(undefined)).toBeUndefined();
+ expect(parseWorktreeEnterInfo('Created worktree at /tmp/wt.')).toBeUndefined();
+ });
+});
+
+describe('isWorktreeExitContent', () => {
+ it('accepts every successful exit outcome', () => {
+ expect(
+ isWorktreeExitContent(
+ 'Exited worktree. Your work is preserved at /tmp/wt on branch worktree-a. Session is now back in /repo.',
+ ),
+ ).toBe(true);
+ expect(
+ isWorktreeExitContent(
+ 'Exited and removed worktree at /tmp/wt. Discarded 3 uncommitted files. Session is now back in /repo.',
+ ),
+ ).toBe(true);
+ expect(
+ isWorktreeExitContent(
+ 'Exited worktree but could not remove it — kept at /tmp/wt. Session is now back in /repo.',
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects the no-op and anything else', () => {
+ expect(isWorktreeExitContent('No-op: there is no active EnterWorktree session to exit.')).toBe(
+ false,
+ );
+ expect(isWorktreeExitContent(undefined)).toBe(false);
+ });
+});
+
+describe('recordWorktreeEnter', () => {
+ it('records the worktree and its branch onto the run topic', async () => {
+ chatMocks.topics = { t1: PR_TOPIC };
+
+ await recordWorktreeEnter({ content: enterCreated('/repo/wt', 'worktree-a'), topicId: 't1' });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/repo/wt', branch: 'worktree-a', isWorktree: true },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('does not record a subagent-only worktree move', async () => {
+ chatMocks.topics = { t1: PR_TOPIC };
+ await recordWorktreeEnter({ content: enterPinnedAgent('/repo/wt'), topicId: 't1' });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the worktree resolves to the source path', async () => {
+ chatMocks.topics = { t1: PR_TOPIC };
+ await recordWorktreeEnter({ content: enterExisting('/repo'), topicId: 't1' });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('is idempotent when already in that worktree', async () => {
+ chatMocks.topics = {
+ t1: {
+ metadata: {
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/repo/wt', isWorktree: true },
+ path: '/repo',
+ },
+ },
+ },
+ };
+ await recordWorktreeEnter({ content: enterExisting('/repo/wt'), topicId: 't1' });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+});
+
+describe('recordWorktreeExit', () => {
+ const IN_WORKTREE = {
+ metadata: {
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/repo/wt', branch: 'worktree-a', isWorktree: true },
+ path: '/repo',
+ },
+ },
+ };
+
+ it('clears the worktree when the session exits and keeps it on disk', async () => {
+ chatMocks.topics = { t1: IN_WORKTREE };
+
+ await recordWorktreeExit({
+ content: 'Exited worktree. Your work is preserved at /repo/wt. Session is now back in /repo.',
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },
+ });
+ });
+
+ it('clears the worktree when it is removed', async () => {
+ chatMocks.topics = { t1: IN_WORKTREE };
+
+ await recordWorktreeExit({
+ content: 'Exited and removed worktree at /repo/wt. Session is now back in /repo.',
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },
+ });
+ });
+
+ it('drops the linked PR with the worktree branch it belonged to', async () => {
+ chatMocks.topics = {
+ t1: {
+ metadata: {
+ workingDirectoryConfig: {
+ git: {
+ activeWorktree: '/repo/wt',
+ branch: 'worktree-a',
+ github: { pullRequest: { number: 7 }, pullRequestStatus: 'ok' },
+ isWorktree: true,
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ },
+ };
+
+ await recordWorktreeExit({
+ content: 'Exited and removed worktree at /repo/wt.',
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo', repoType: 'github' },
+ });
+ });
+
+ it('does nothing for the no-op exit message', async () => {
+ chatMocks.topics = { t1: IN_WORKTREE };
+ await recordWorktreeExit({
+ content: 'No-op: there is no active EnterWorktree session to exit.',
+ topicId: 't1',
+ });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the topic is not in a worktree', async () => {
+ chatMocks.topics = { t1: PR_TOPIC };
+ await recordWorktreeExit({
+ content: 'Exited and removed worktree at /repo/wt.',
+ 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.ts
index 700062cd3c3..8f67934856e 100644
--- a/src/store/tool/slices/builtin/executors/heteroCli.ts
+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts
@@ -1,7 +1,11 @@
import type { ToolAfterCallContext } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
-import { recordGitCommandEffects } from './worktreeDetection';
+import {
+ recordGitCommandEffects,
+ recordWorktreeEnter,
+ recordWorktreeExit,
+} from './worktreeDetection';
/**
* Hook-only executor for a heterogeneous CLI agent's tool identifier
@@ -33,6 +37,17 @@ const readShellCommand = (params: unknown): string | string[] | undefined => {
return undefined;
};
+/**
+ * The CLI's own worktree tools, when it has any. Claude Code moves its session with
+ * `EnterWorktree` / `ExitWorktree` and never shells out, so the `git worktree add`
+ * sniffing in `recordGitCommandEffects` cannot observe those moves. Codex has no
+ * equivalent tool and so passes `undefined`.
+ */
+interface WorktreeApiNames {
+ enter: string;
+ exit: string;
+}
+
class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
protected readonly apiEnum = EMPTY_API_ENUM;
@@ -41,10 +56,12 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
* @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.
+ * @param worktreeApiNames The adapter's native enter/exit worktree tools, if any.
*/
constructor(
readonly identifier: string,
private readonly shellApiNames: ReadonlySet<string>,
+ private readonly worktreeApiNames?: WorktreeApiNames,
) {
super();
}
@@ -55,8 +72,21 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
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;
+ // Constrain to a SUCCESSFUL call bound to a run topic. A refused `ExitWorktree`
+ // (dirty worktree, no active session) fails validation and lands here with
+ // `success: false` — it must not clear the topic's worktree.
+ if (!result.success || !topicId) return;
+
+ if (apiName === this.worktreeApiNames?.enter) {
+ await recordWorktreeEnter({ content: result.content, topicId });
+ return;
+ }
+ if (apiName === this.worktreeApiNames?.exit) {
+ await recordWorktreeExit({ content: result.content, topicId });
+ return;
+ }
+
+ if (!this.shellApiNames.has(apiName)) return;
const command = readShellCommand(params);
if (command === undefined) return;
@@ -66,5 +96,8 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
}
// CC's shell tool is `Bash`; Codex's is `command_execution`.
-export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']));
+export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']), {
+ enter: 'EnterWorktree',
+ exit: 'ExitWorktree',
+});
export const codexExecutor = new HeteroCliExecutor('codex', new Set(['command_execution']));
diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
index 79c2768341e..f7096bcbc70 100644
--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts
+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
@@ -61,6 +61,23 @@ const BRANCH_OUTPUT_PATTERNS = [
/branch ['"]([^'"\n]+)['"] set up to track/i,
] as const;
+/**
+ * Claude Code's `EnterWorktree` / `ExitWorktree` move the session without ever
+ * shelling out, so the `git worktree add` sniffing above cannot see them. Their
+ * tool_result ships only CC's `message` string (the structured `worktreePath`
+ * never leaves the tool), which makes these sentences the wire contract.
+ */
+const CC_ENTER_PATTERN = /^(?:Created|Entered) worktree at (.+?)(?: on branch (\S+))?\. /;
+const CC_EXIT_PATTERN = /^Exited\b/;
+/**
+ * Said only on the branch that `chdir`s the SESSION into the worktree. A subagent
+ * pinned to its own cwd gets "This agent's working directory …" instead, because it
+ * moved only itself — recording that would claim the whole run had relocated.
+ * Requiring this sentence fails CLOSED: if CC rewords it we stop recording, rather
+ * than record a worktree the session is not in.
+ */
+const CC_SESSION_ENTER_MARKER = 'The session is now working in the worktree';
+
interface WorktreeAddInfo {
branch?: string;
path: string;
@@ -413,6 +430,35 @@ const applyWorktreeAddToConfig = (
};
};
+/**
+ * The session left the worktree and is back in the source repo. `branch` and the
+ * linked `github` PR described the worktree's branch, not the source repo's, so they
+ * are dropped rather than left pointing at a branch the topic is no longer on — the
+ * source branch is unknown until the next `git switch` / `checkout` refreshes it.
+ */
+const applyWorktreeExitToConfig = (
+ currentConfig: WorkingDirConfig | undefined,
+ source: string,
+): WorkingDirConfig => {
+ const git: NonNullable<WorkingDirConfig['git']> = {
+ ...currentConfig?.git,
+ isWorktree: false,
+ };
+
+ delete git.activeWorktree;
+ if (currentConfig?.git?.isWorktree) {
+ delete git.branch;
+ delete git.github;
+ }
+
+ return {
+ ...currentConfig,
+ git,
+ path: source,
+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),
+ };
+};
+
/** Collapse `.`/`..` segments in a POSIX path without touching the filesystem. */
const normalizePosix = (p: string): string => {
const isAbs = p.startsWith('/');
@@ -611,3 +657,87 @@ export const recordGitCommandEffects = async (params: {
if (isEqual(currentConfig, nextConfig)) return;
await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });
};
+
+/**
+ * Read the worktree CC entered out of `EnterWorktree`'s result message:
+ *
+ * `${'Created' | 'Entered'} worktree at ${path}[ on branch ${branch}]. The session…`
+ *
+ * The path is delimited by ` on branch <ref>` or the `. ` before the next sentence,
+ * so a path containing spaces survives; one containing `". "` would not. Returns
+ * undefined unless the SESSION moved (see {@link CC_SESSION_ENTER_MARKER}).
+ */
+export const parseWorktreeEnterInfo = (content?: string): WorktreeAddInfo | undefined => {
+ if (!content?.includes(CC_SESSION_ENTER_MARKER)) return undefined;
+
+ const match = CC_ENTER_PATTERN.exec(content);
+ const path = match?.[1]?.trim();
+ if (!path) return undefined;
+
+ const branch = normalizeBranch(match?.[2]);
+ return { ...(branch ? { branch } : {}), path };
+};
+
+/**
+ * Every successful `ExitWorktree` outcome — kept, removed, or "could not remove it"
+ * — opens with `Exited …`, and all three leave the session back in its original
+ * directory. The no-op ("no active EnterWorktree session") and the refusals are
+ * validation failures, so they arrive with `success: false` and never get here.
+ */
+export const isWorktreeExitContent = (content?: string): boolean =>
+ !!content && CC_EXIT_PATTERN.test(content);
+
+/**
+ * Record a successful `EnterWorktree` as the run topic's active worktree. Unlike
+ * `git worktree add`, the path is never in the arguments — a bare call generates a
+ * random name — so it is read back out of the result message.
+ */
+export const recordWorktreeEnter = async (params: {
+ content?: string;
+ topicId: string;
+}): Promise<void> => {
+ const { content, topicId } = params;
+ const state = getChatStoreState();
+
+ const topic = topicSelectors.getTopicById(topicId)(state);
+ const currentConfig = topic?.metadata?.workingDirectoryConfig;
+ const source = getWorkingDirSourcePath(currentConfig) ?? topic?.metadata?.workingDirectory;
+
+ const worktreeInfo = parseWorktreeEnterInfo(content);
+ if (!worktreeInfo || !source || worktreeInfo.path === source) return;
+
+ const nextConfig = applyWorktreeAddToConfig(currentConfig, source, worktreeInfo);
+
+ if (isEqual(currentConfig, nextConfig)) return;
+ await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });
+};
+
+/**
+ * Record a successful `ExitWorktree` — the session is back in its original directory,
+ * so the topic drops its worktree whether it was kept on disk or removed. Keeping it
+ * would leave the topic pointing at a directory the run has left (and, on `remove`,
+ * one that no longer exists).
+ */
+export const recordWorktreeExit = async (params: {
+ content?: string;
+ topicId: string;
+}): Promise<void> => {
+ const { content, topicId } = params;
+ if (!isWorktreeExitContent(content)) return;
+
+ const state = getChatStoreState();
+
+ const topic = topicSelectors.getTopicById(topicId)(state);
+ const currentConfig = topic?.metadata?.workingDirectoryConfig;
+ const source = getWorkingDirSourcePath(currentConfig) ?? topic?.metadata?.workingDirectory;
+ if (!source) return;
+
+ // Never in a worktree → nothing to clear, and don't materialize an empty `git`.
+ const currentGit = currentConfig?.git;
+ if (!currentGit?.activeWorktree && !currentGit?.isWorktree) return;
+
+ const nextConfig = applyWorktreeExitToConfig(currentConfig, source);
+
+ if (isEqual(currentConfig, nextConfig)) return;
+ await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });
+};