🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(worktree): recover topics stuck on a removed worktree (#21320)
Arvin Xu5157a8ff89af
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 129044a6ef9..4cdb9d91d9f 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2981,10 +2981,13 @@"workflow.toolDisplayName.writeDocument": "Wrote a document","workflow.toolDisplayName.writeLocalFile": "Wrote a file","workflow.working": "Working...",+ "workingDirectoryGuide.actions.resetToSource": "Switch back to {{name}} and retry","workingDirectoryGuide.actions.retry": "Retry","workingDirectoryGuide.desc": "The working directory saved for this conversation no longer exists.","workingDirectoryGuide.hint": "Choose an existing folder from the working directory selector, then retry this message.",+ "workingDirectoryGuide.resetFailed": "Could not switch back to the main directory. Please try again.","workingDirectoryGuide.title": "Working directory unavailable",+ "workingDirectoryGuide.worktreeHint": "This conversation was still in a worktree that has since been removed. Switch back to the main directory to keep working.","workingPanel.agentDocuments": "Agent Documents","workingPanel.browser.actions.back": "Back","workingPanel.browser.actions.capture": "Add screenshot to chat input",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex aaff2ca590e..e61598e5f2b 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2981,10 +2981,13 @@"workflow.toolDisplayName.writeDocument": "撰写了文档","workflow.toolDisplayName.writeLocalFile": "写入了文件","workflow.working": "处理中...",+ "workingDirectoryGuide.actions.resetToSource": "切回 {{name}} 并重试","workingDirectoryGuide.actions.retry": "重试","workingDirectoryGuide.desc": "此会话保存的工作目录已不存在。","workingDirectoryGuide.hint": "请从工作目录选择器中选择一个仍然存在的目录,然后重试这条消息。",+ "workingDirectoryGuide.resetFailed": "切回主目录失败,请重试。","workingDirectoryGuide.title": "工作目录不可用",+ "workingDirectoryGuide.worktreeHint": "此会话仍停留在一个已被删除的 worktree 中。切回主目录即可继续工作。","workingPanel.agentDocuments": "代理文档","workingPanel.browser.actions.back": "后退","workingPanel.browser.actions.capture": "截图并添加到输入框",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 969a8980a1e..b70de9622bc 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1311,12 +1311,17 @@ export default {'grokBuildInstallGuide.menuNotification.title': 'Grok Build CLI not found','grokBuildInstallGuide.reason': 'LobeHub could not start Grok Build: {{message}}','grokBuildInstallGuide.title': 'Install Grok Build CLI',+ 'workingDirectoryGuide.actions.resetToSource': 'Switch back to {{name}} and retry','workingDirectoryGuide.actions.retry': 'Retry','workingDirectoryGuide.desc':'The working directory saved for this conversation no longer exists.','workingDirectoryGuide.hint':'Choose an existing folder from the working directory selector, then retry this message.',+ 'workingDirectoryGuide.resetFailed':+ 'Could not switch back to the main directory. Please try again.','workingDirectoryGuide.title': 'Working directory unavailable',+ 'workingDirectoryGuide.worktreeHint':+ 'This conversation was still in a worktree that has since been removed. Switch back to the main directory to keep working.','opencodeInstallGuide.actions.openDocs': 'Open Install Guide','opencodeInstallGuide.actions.openSystemTools': 'Open System Tools','opencodeInstallGuide.afterInstall':diff --git a/src/features/Conversation/Error/WorkingDirectoryStatusGuide.tsx b/src/features/Conversation/Error/WorkingDirectoryStatusGuide.tsxnew file mode 100644index 00000000000..ec3316c43aa--- /dev/null+++ b/src/features/Conversation/Error/WorkingDirectoryStatusGuide.tsx@@ -0,0 +1,64 @@+import { toast } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';+import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';+import type {+ HeterogeneousAgentStatusGuideProps,+ HeterogeneousAgentWorkingDirectoryResetState,+} from '@/features/Electron/HeterogeneousAgent/StatusGuide/types';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';++import { getMissingWorkingDirectory, resolveStaleWorktreeReset } from './staleWorktreeReset';++interface WorkingDirectoryStatusGuideProps extends HeterogeneousAgentStatusGuideProps {+ agentId: string;+ topicId: string;+}++/**+ * The "working directory not found" guide, plus a way back when the missing+ * directory is a deleted worktree. Mounted only for that error so the+ * working-directory hooks don't run under every error card.+ */+const WorkingDirectoryStatusGuide = memo<WorkingDirectoryStatusGuideProps>(+ ({ agentId, topicId, ...props }) => {+ const { t } = useTranslation('chat');+ const config = useChatStore(+ (s) => topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig,+ );+ // Same funnel as the control bar's stale-snapshot reset and worktree+ // dropdown, so the topic write (and its project-root guard) can't drift.+ const { commit } = useCommitWorkingDirectory(agentId, topicId);++ const reset = resolveStaleWorktreeReset(config, getMissingWorkingDirectory(props.error));+ const { onRetry } = props;++ const workingDirectoryReset: HeterogeneousAgentWorkingDirectoryResetState | undefined =+ reset && onRetry+ ? {+ name: reset.name,+ onReset: async () => {+ try {+ await commit(reset.entry);+ } catch (error) {+ console.error('[WorkingDirectoryStatusGuide] Failed to reset worktree:', error);+ toast.error(t('workingDirectoryGuide.resetFailed'));+ return;+ }+ onRetry();+ },+ }+ : undefined;++ return (+ <HeterogeneousAgentStatusGuide {...props} workingDirectoryReset={workingDirectoryReset} />+ );+ },+);++WorkingDirectoryStatusGuide.displayName = 'WorkingDirectoryStatusGuide';++export default WorkingDirectoryStatusGuide;diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex b24fc73aba0..bc06f48cfb7 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -31,6 +31,7 @@ const conversationContextMock = vi.hoisted(},);const createTopicForwardModalMock = vi.hoisted(() => vi.fn());+const commitWorkingDirectoryMock = vi.hoisted(() => vi.fn());// Stands in for whatever card a downstream build installs into the business slot.const businessSlot = vi.hoisted(() => ({ render: false }));const missingTranslationKeys = vi.hoisted(() => new Set<string>());@@ -109,22 +110,33 @@ vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({onDismiss,onRetry,onTransfer,+ workingDirectoryReset,}: {agentType?: string;error?: { code?: string };onDismiss?: () => void;onRetry?: () => void;onTransfer?: () => void;+ workingDirectoryReset?: { name?: string; onReset: () => Promise<void> };}) => (<div>{`guide:${agentType}:${error?.code}`}{onDismiss && <button onClick={onDismiss}>dismiss</button>}{onRetry && <button onClick={onRetry}>guide-retry</button>}{onTransfer && <button onClick={onTransfer}>transfer</button>}+ {workingDirectoryReset && (+ <button onClick={() => void workingDirectoryReset.onReset()}>+ {`reset-to:${workingDirectoryReset.name}`}+ </button>+ )}</div>),}));+vi.mock('@/features/ChatInput/ControlBar/useCommitWorkingDirectory', () => ({+ useCommitWorkingDirectory: () => ({ commit: commitWorkingDirectoryMock }),+}));+vi.mock('@/services/electron/binary', () => ({binaryService: {detectHeterogeneousAgentCommand: detectHeterogeneousAgentCommandMock,@@ -211,6 +223,8 @@ describe('ErrorMessageExtra', () => {conversationContextMock.agentId = undefined;conversationContextMock.topicId = undefined;createTopicForwardModalMock.mockClear();+ commitWorkingDirectoryMock.mockReset();+ commitWorkingDirectoryMock.mockResolvedValue(undefined);useChatStore.setState({ activeTopicId: null as any, topicDetailMap: {} });});@@ -653,6 +667,89 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText('guide:codex:working_directory_not_found')).toBeInTheDocument();});+ // Regression: a project conversation hides its directory picker, so when the+ // run's `git worktree add` checkout was later removed, the topic kept spawning+ // in the dead worktree and the card's only advice pointed at a hidden picker.+ describe('deleted worktree recovery', () => {+ const renderWorktreeError = () =>+ render(+ <ErrorMessageExtra+ error={{ message: 'response.undefined' }}+ data={{+ error: {+ body: {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.WorkingDirectoryNotFound,+ message: 'Working directory does not exist: /tmp/ibench-push',+ },+ } as any,+ id: 'msg-dead-worktree',+ }}+ />,+ );++ beforeEach(() => {+ conversationContextMock.agentId = 'agent-1';+ conversationContextMock.topicId = 'topic-1';+ displayMessageMock.set('msg-dead-worktree', { parentId: 'user-1' });+ useChatStore.setState({+ topicDetailMap: {+ 'topic-1': {+ id: 'topic-1',+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree: '/tmp/ibench-push', isWorktree: true },+ path: '/Users/me/ibench/landing',+ },+ },+ projectWorkingDirectoryId: 'dir-1',+ title: 'Topic',+ } as any,+ },+ });+ });++ it('switches back to the source repo, then retries', async () => {+ renderWorktreeError();++ fireEvent.click(screen.getByText('reset-to:landing'));++ await waitFor(() =>+ expect(delAndRegenerateMessageMock).toHaveBeenCalledWith('msg-dead-worktree'),+ );+ expect(commitWorkingDirectoryMock).toHaveBeenCalledWith({ path: '/Users/me/ibench/landing' });+ expect(commitWorkingDirectoryMock.mock.invocationCallOrder[0]).toBeLessThan(+ delAndRegenerateMessageMock.mock.invocationCallOrder[0],+ );+ });++ it('does not retry into the dead worktree when the switch fails', async () => {+ commitWorkingDirectoryMock.mockRejectedValue(new Error('offline'));+ renderWorktreeError();++ fireEvent.click(screen.getByText('reset-to:landing'));++ await waitFor(() => expect(commitWorkingDirectoryMock).toHaveBeenCalled());+ expect(delAndRegenerateMessageMock).not.toHaveBeenCalled();+ });++ it('offers no reset when the topic records no worktree', () => {+ useChatStore.setState({+ topicDetailMap: {+ 'topic-1': {+ id: 'topic-1',+ metadata: { workingDirectoryConfig: { path: '/Users/me/ibench/landing' } },+ title: 'Topic',+ } as any,+ },+ });+ renderWorktreeError();++ expect(screen.queryByText(/reset-to:/)).not.toBeInTheDocument();+ expect(screen.getByText('guide-retry')).toBeInTheDocument();+ });+ });+it('dismisses only the current heterogeneous error field', () => {render(<ErrorMessageExtradiff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 2336cef215b..b0c8fdf872d 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -27,7 +27,10 @@ import {useConversationStore,} from '@/features/Conversation/store';import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';-import type { HeterogeneousAgentScheduleState } from '@/features/Electron/HeterogeneousAgent/StatusGuide/types';+import type {+ HeterogeneousAgentScheduleState,+ HeterogeneousAgentStatusGuideProps,+} from '@/features/Electron/HeterogeneousAgent/StatusGuide/types';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { useProviderName } from '@/hooks/useProviderName';@@ -43,6 +46,7 @@ import { readClientLlmWait } from './clientLlmWait';import { type DedicatedErrorCardType, isDedicatedErrorCardType } from './dedicatedErrorCards';import { isHeterogeneousAgentStatusGuideError } from './heterogeneous';import { useHeterogeneousAutoRetry } from './useHeterogeneousAutoRetry';+import WorkingDirectoryStatusGuide from './WorkingDirectoryStatusGuide';// Re-export so existing barrel consumers (ContentBlock, message action bar) can// keep importing the guard from '@/features/Conversation/Error'.@@ -471,36 +475,50 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(: undefined;if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {- return (- <HeterogeneousAgentStatusGuide- agentType={sessionErrorBody.agentType}- autoRetry={autoRetry}- error={sessionErrorBody}- schedule={schedule}- onDismiss={() => void updateMessageError(data.id, null)}- onRetry={() => void handleHeterogeneousRetry()}- onOpenSystemTools={() =>- navigate(- isDesktop- ? '/settings/system-tools'- : activeAgentId- ? `/agent/${activeAgentId}/profile`- : '/settings/credential',- )- }- onTransfer={- isRateLimitError && conversationAgentId && conversationTopicId- ? () =>- createTopicForwardModal({- cancelSourceContinuation: true,- sourceAgentId: conversationAgentId,- topicId: conversationTopicId,- topicTitle: conversationTopic?.title || '',- })- : undefined- }- />- );+ const guideProps: HeterogeneousAgentStatusGuideProps = {+ agentType: sessionErrorBody.agentType,+ autoRetry,+ error: sessionErrorBody,+ onDismiss: () => void updateMessageError(data.id, null),+ onOpenSystemTools: () =>+ navigate(+ isDesktop+ ? '/settings/system-tools'+ : activeAgentId+ ? `/agent/${activeAgentId}/profile`+ : '/settings/credential',+ ),+ onRetry: () => void handleHeterogeneousRetry(),+ onTransfer:+ isRateLimitError && conversationAgentId && conversationTopicId+ ? () =>+ createTopicForwardModal({+ cancelSourceContinuation: true,+ sourceAgentId: conversationAgentId,+ topicId: conversationTopicId,+ topicTitle: conversationTopic?.title || '',+ })+ : undefined,+ schedule,+ };++ // A deleted worktree is recoverable from the card itself (back to the+ // source repo), which a retry-only card can't offer.+ if (+ canRetry &&+ sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.WorkingDirectoryNotFound &&+ conversationAgentId &&+ conversationTopicId+ )+ return (+ <WorkingDirectoryStatusGuide+ {...guideProps}+ agentId={conversationAgentId}+ topicId={conversationTopicId}+ />+ );++ return <HeterogeneousAgentStatusGuide {...guideProps} />;}// A run parked in `waiting_for_client` is still alive: show what it waitsdiff --git a/src/features/Conversation/Error/staleWorktreeReset.test.ts b/src/features/Conversation/Error/staleWorktreeReset.test.tsnew file mode 100644index 00000000000..e406e069f4a--- /dev/null+++ b/src/features/Conversation/Error/staleWorktreeReset.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';++import { getMissingWorkingDirectory, resolveStaleWorktreeReset } from './staleWorktreeReset';++describe('resolveStaleWorktreeReset', () => {+ it('offers the source repo when the topic still records a deleted worktree', () => {+ expect(+ resolveStaleWorktreeReset(+ {+ git: { activeWorktree: '/tmp/ibench-push', branch: 'tj/fix', isWorktree: true },+ path: '/Users/me/ibench/landing',+ },+ '/tmp/ibench-push',+ ),+ ).toEqual({ entry: { path: '/Users/me/ibench/landing' }, name: 'landing' });+ });++ it('keeps the recorded repo type', () => {+ expect(+ resolveStaleWorktreeReset({+ git: { activeWorktree: '/tmp/wt' },+ path: '/repo',+ repoType: 'github',+ })?.entry,+ ).toEqual({ path: '/repo', repoType: 'github' });+ });++ it('offers nothing without a worktree override', () => {+ expect(resolveStaleWorktreeReset({ path: '/repo' })).toBeUndefined();+ expect(resolveStaleWorktreeReset(undefined)).toBeUndefined();+ expect(+ resolveStaleWorktreeReset({ git: { activeWorktree: '/repo' }, path: '/repo' }),+ ).toBeUndefined();+ });++ it('offers nothing when the source repo itself is the missing directory', () => {+ expect(+ resolveStaleWorktreeReset({ git: { activeWorktree: '/tmp/wt' }, path: '/repo' }, '/repo'),+ ).toBeUndefined();+ });++ it('offers nothing when the error names an older worktree the topic has left', () => {+ expect(+ resolveStaleWorktreeReset(+ { git: { activeWorktree: '/tmp/wt-b' }, path: '/repo' },+ '/tmp/wt-a',+ ),+ ).toBeUndefined();+ });+});++describe('getMissingWorkingDirectory', () => {+ it('prefers the structured field', () => {+ expect(getMissingWorkingDirectory({ message: 'anything', workingDirectory: '/tmp/wt' })).toBe(+ '/tmp/wt',+ );+ });++ it('reads the path from the spawn guard message', () => {+ expect(+ getMissingWorkingDirectory({ message: 'Working directory does not exist: /tmp/wt' }),+ ).toBe('/tmp/wt');+ expect(+ getMissingWorkingDirectory({ message: 'Working directory is not a directory: /tmp/f' }),+ ).toBe('/tmp/f');+ });++ it('returns undefined when no path is known', () => {+ expect(getMissingWorkingDirectory({ message: 'spawn failed' })).toBeUndefined();+ expect(getMissingWorkingDirectory(undefined)).toBeUndefined();+ expect(getMissingWorkingDirectory(null)).toBeUndefined();+ });+});diff --git a/src/features/Conversation/Error/staleWorktreeReset.ts b/src/features/Conversation/Error/staleWorktreeReset.tsnew file mode 100644index 00000000000..0651e9b25a2--- /dev/null+++ b/src/features/Conversation/Error/staleWorktreeReset.ts@@ -0,0 +1,54 @@+import type { WorkingDirConfig, WorkingDirEntry } from '@lobechat/types';++import {+ getWorkingDirectoryName,+ getWorkingDirectoryPathString,+} from '@/helpers/workingDirectoryPath';++export interface StaleWorktreeReset {+ /** The entry to commit: the source repo with the worktree override dropped. */+ entry: WorkingDirEntry;+ /** The source repo's folder name, for the button label. */+ name?: string;+}++/**+ * The way out of a "working directory not found" failure caused by a deleted+ * worktree: the topic still records `git.activeWorktree`, so every retry spawns+ * in the dead checkout. Falling back to the source repo the worktree was linked+ * from is always safe — the CLI session is anchored there — and is the only+ * recovery a project conversation has, since its directory picker is hidden.+ *+ * Undefined when there is no worktree override to drop, or when the error names+ * a directory other than the recorded worktree — the source repo itself, or an+ * older worktree the topic has since moved on from. An error without a path+ * keeps the offer.+ */+export const resolveStaleWorktreeReset = (+ config: WorkingDirConfig | undefined,+ missingPath?: string,+): StaleWorktreeReset | undefined => {+ const sourcePath = getWorkingDirectoryPathString(config?.path);+ const worktreePath = getWorkingDirectoryPathString(config?.git?.activeWorktree);+ if (!sourcePath || !worktreePath || worktreePath === sourcePath) return undefined;+ if (missingPath && missingPath !== worktreePath) return undefined;++ return {+ // The branch, upstream and PR described the worktree's branch, not the+ // source repo's, so they go with it — same as an `ExitWorktree`.+ entry: { path: sourcePath, ...(config?.repoType ? { repoType: config.repoType } : {}) },+ name: getWorkingDirectoryName(sourcePath),+ };+};++const MISSING_DIRECTORY_MESSAGE = /^Working directory (?:does not exist|is not a directory): (.+)$/;++/**+ * The directory a working-directory failure names. Persisted errors may carry+ * only the message the desktop spawn guard wrote, so fall back to reading it.+ */+export const getMissingWorkingDirectory = (+ error?: { message?: string; workingDirectory?: string } | null,+): string | undefined =>+ getWorkingDirectoryPathString(error?.workingDirectory) ??+ getWorkingDirectoryPathString(MISSING_DIRECTORY_MESSAGE.exec(error?.message ?? '')?.[1]);diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsxindex a72c12b01ef..03f2de5ec04 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx@@ -23,6 +23,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(onTransfer,schedule,variant = 'inline',+ workingDirectoryReset,}) => {const config = resolveHeterogeneousAgentGuideConfig({agentType,@@ -38,6 +39,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(onTransfer,schedule,variant,+ workingDirectoryReset,};switch (error?.code) {diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/WorkingDirectoryState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/WorkingDirectoryState.tsxindex fb8b1760be4..ae534e4f550 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/WorkingDirectoryState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/WorkingDirectoryState.tsx@@ -1,13 +1,30 @@-import { Text } from '@lobehub/ui';-import { FolderX } from 'lucide-react';+import { Button, Flexbox, Text } from '@lobehub/ui';+import { FolderX, Undo2 } from 'lucide-react';+import { useState } from 'react';import { useTranslation } from 'react-i18next';import GuideActions from '../GuideActions';import GuideShell from '../GuideShell';import type { HeterogeneousAgentGuideStateProps } from '../types';-const WorkingDirectoryState = ({ error, onRetry, variant }: HeterogeneousAgentGuideStateProps) => {+const WorkingDirectoryState = ({+ error,+ onRetry,+ variant,+ workingDirectoryReset,+}: HeterogeneousAgentGuideStateProps) => {const { t } = useTranslation('chat');+ const [resetting, setResetting] = useState(false);++ const handleReset = async () => {+ if (!workingDirectoryReset || resetting) return;+ setResetting(true);+ try {+ await workingDirectoryReset.onReset();+ } finally {+ setResetting(false);+ }+ };return (<GuideShell@@ -16,16 +33,37 @@ const WorkingDirectoryState = ({ error, onRetry, variant }: HeterogeneousAgentGutitle={t('workingDirectoryGuide.title')}variant={variant}actions={- <GuideActions- retryPrimary- retryLabel={t('workingDirectoryGuide.actions.retry')}- onRetry={onRetry}- />+ workingDirectoryReset ? (+ // A deleted worktree has one real way out — back to the source repo —+ // so it leads; a bare retry would only spawn in the dead checkout again.+ <Flexbox horizontal gap={8} justify="flex-end">+ <Button+ icon={<Undo2 size={14} />}+ loading={resetting}+ type="primary"+ onClick={handleReset}+ >+ {t('workingDirectoryGuide.actions.resetToSource', {+ name: workingDirectoryReset.name,+ })}+ </Button>+ </Flexbox>+ ) : (+ <GuideActions+ retryPrimary+ retryLabel={t('workingDirectoryGuide.actions.retry')}+ onRetry={onRetry}+ />+ )}>{error?.workingDirectory && <Text code>{error.workingDirectory}</Text>}<Text style={{ fontSize: 12 }} type="secondary">- {t('workingDirectoryGuide.hint')}+ {t(+ workingDirectoryReset+ ? 'workingDirectoryGuide.worktreeHint'+ : 'workingDirectoryGuide.hint',+ )}</Text></GuideShell>);diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex 78cef736552..2a7859eea5e 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -32,6 +32,12 @@ export interface HeterogeneousAgentScheduleState {resetsAt?: number;}+export interface HeterogeneousAgentWorkingDirectoryResetState {+ /** Folder name of the source repo the conversation goes back to. */+ name?: string;+ onReset: () => Promise<void>;+}+export interface HeterogeneousAgentStatusGuideProps {agentType?: string;autoRetry?: HeterogeneousAgentAutoRetryState;@@ -42,6 +48,11 @@ export interface HeterogeneousAgentStatusGuideProps {onTransfer?: () => void;schedule?: HeterogeneousAgentScheduleState;variant?: HeterogeneousAgentStatusGuideVariant;+ /**+ * Present when the missing directory is a deleted worktree the conversation+ * still records: drops it, falls back to the source repo and retries.+ */+ workingDirectoryReset?: HeterogeneousAgentWorkingDirectoryResetState;}export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = LOCAL_HETEROGENEOUS_AGENT_TYPES;@@ -67,4 +78,5 @@ export interface HeterogeneousAgentGuideStateProps {onTransfer?: () => void;schedule?: HeterogeneousAgentScheduleState;variant: HeterogeneousAgentStatusGuideVariant;+ workingDirectoryReset?: HeterogeneousAgentWorkingDirectoryResetState;}diff --git a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.tsnew file mode 100644index 00000000000..1a3f69e6413--- /dev/null+++ b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts@@ -0,0 +1,186 @@+import type {+ DeviceGitLinkedPullRequest,+ DeviceGitUpstreamRef,+ WorkingDirConfig,+} from '@lobechat/types';++/**+ * How each detected git / gh side effect rewrites a topic's working-directory+ * config. Pure reducers, so `worktreeDetection` decides WHAT happened and these+ * decide what the topic records about it.+ */++export interface WorktreeAddInfo {+ branch?: string;+ path: string;+}++export interface PullRequestCreateInfo {+ branch?: string;+ pullRequest: DeviceGitLinkedPullRequest;+}++export const applyBranchToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ branch: string,+): WorkingDirConfig => {+ const branchChanged = currentConfig?.git?.branch !== branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ branch,+ };++ delete git.detached;+ // The old branch's remote ref and PR describe a branch the topic has left. Held+ // onto, `upstream` would aim the PR lookup at the wrong head — worse than none.+ if (branchChanged) {+ delete git.github;+ delete git.upstream;+ }++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};++export const applyDetachedToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+): WorkingDirConfig => {+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ detached: true,+ };++ delete git.branch;+ delete git.github;+ delete git.upstream;++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};++export const applyPullRequestToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ info: PullRequestCreateInfo,+): WorkingDirConfig => {+ const branch = info.branch ?? currentConfig?.git?.branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ ...(branch ? { branch } : {}),+ github: {+ pullRequest: info.pullRequest,+ pullRequestStatus: 'ok',+ },+ };++ delete git.detached;++ return {+ ...currentConfig,+ git,+ path: source,+ repoType: 'github',+ };+};++/**+ * Record where the branch now publishes to. This is what makes the PR lookup work at+ * all for a worktree: its local branch name (`worktree-feat+x`) never exists on the+ * remote, so only the ref the push actually created (`feat/y`) can find the PR.+ */+export const applyPushToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ upstream: DeviceGitUpstreamRef,+): WorkingDirConfig => {+ const previous = currentConfig?.git?.upstream?.branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ upstream,+ };++ // Re-pointing the branch at a DIFFERENT remote ref orphans the PR bound to the old+ // one. Only a change invalidates it — a first push must not drop a PR that a+ // preceding `gh pr create` in the same run just recorded.+ if (previous && previous !== upstream.branch) delete git.github;++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};++export const applyWorktreeAddToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+ info: WorktreeAddInfo,+): WorkingDirConfig => {+ const branchChanged = !!info.branch && currentConfig?.git?.branch !== info.branch;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ activeWorktree: info.path,+ ...(info.branch ? { branch: info.branch } : {}),+ isWorktree: true,+ };++ if (info.branch) delete git.detached;+ if (branchChanged) {+ delete git.github;+ delete git.upstream;+ }++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};++/**+ * The session left the worktree and is back in the source repo. `branch`, its+ * `upstream` ref 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.+ */+export const applyWorktreeExitToConfig = (+ currentConfig: WorkingDirConfig | undefined,+ source: string,+): WorkingDirConfig => {+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ isWorktree: false,+ };++ // A worktree picked by hand records no `isWorktree` flag — a distinct+ // `activeWorktree` is evidence enough that branch / upstream / PR were its own.+ const activeWorktree = currentConfig?.git?.activeWorktree;+ const leftWorktree =+ !!currentConfig?.git?.isWorktree || (!!activeWorktree && activeWorktree !== source);+ delete git.activeWorktree;+ if (leftWorktree) {+ delete git.branch;+ delete git.github;+ delete git.upstream;+ }++ return {+ ...currentConfig,+ git,+ path: source,+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ };+};diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.tsnew file mode 100644index 00000000000..d83ff586612--- /dev/null+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.ts@@ -0,0 +1,316 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { recordGitCommandEffects } from './worktreeDetection';++const listGitWorktrees = vi.hoisted(() => vi.fn());++const chatMocks = vi.hoisted(() => ({+ topics: {} as Record<string, { metadata?: Record<string, any> }>,+ updateTopicMetadata: vi.fn(),+}));++vi.mock('@/store/device/gitStatus/store', () => ({+ getGitStatusStoreState: () => ({ revalidateGitStatus: vi.fn() }),+}));++vi.mock('@/store/chat/store', () => ({+ getChatStoreState: () => chatMocks,+}));++vi.mock('@/store/chat/selectors', () => ({+ topicSelectors: {+ getTopicById: (id: string) => (state: typeof chatMocks) => state.topics[id],+ },+}));++vi.mock('@/services/git', () => ({+ gitService: { listGitWorktrees },+}));++vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'device-1' } }),+}));++const setTopicWorktree = (activeWorktree: string) => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree, branch: 'fix/tab-nav', isWorktree: true },+ path: '/repo',+ },+ },+ },+ };+};++// Regression: a run that added a scratch worktree, pushed from it and then+// removed it kept the topic's `activeWorktree`, so every later run in that+// conversation failed with "working directory does not exist".+describe('recordGitCommandEffects — git worktree remove', () => {+ beforeEach(() => {+ chatMocks.updateTopicMetadata.mockReset();+ // The device's view after the command: only the source checkout is left.+ listGitWorktrees.mockReset();+ listGitWorktrees.mockResolvedValue([{ branch: 'main', path: '/repo' }]);+ });++ it('returns the topic to its source repo when the active worktree is removed', async () => {+ setTopicWorktree('/tmp/repo-push');++ await recordGitCommandEffects({+ command:+ 'git worktree remove /tmp/repo-push && git branch -D fix/tab-nav -q; git status --short',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });++ it('resolves a relative path and skips flags', async () => {+ setTopicWorktree('/repo/.worktrees/wt');++ await recordGitCommandEffects({+ command: 'git worktree remove --force .worktrees/wt',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });++ it('expands a variable used as the git -C directory', async () => {+ setTopicWorktree('/repo/.worktrees/wt');++ await recordGitCommandEffects({+ command: 'BASE=/repo; git -C "$BASE" worktree remove .worktrees/wt',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });++ it('handles the shell-wrapped argv form', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({+ command: ['/bin/zsh', '-lc', 'git worktree remove /tmp/wt'],+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledTimes(1);+ });++ it('still clears the active worktree when the command removes another one after it', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({+ command: 'git worktree remove /tmp/wt && git worktree remove /tmp/other',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });++ it('keeps the worktree when a conditional removal never ran on the device', async () => {+ setTopicWorktree('/tmp/wt');+ listGitWorktrees.mockResolvedValue([+ { branch: 'main', path: '/repo' },+ { branch: 'fix/tab-nav', path: '/tmp/wt' },+ ]);++ await recordGitCommandEffects({+ command: 'test -f marker && git worktree remove /tmp/wt || true',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('keeps the worktree when the device cannot confirm the removal', async () => {+ setTopicWorktree('/tmp/wt');+ listGitWorktrees.mockRejectedValue(new Error('device offline'));++ await recordGitCommandEffects({ command: 'git worktree remove /tmp/wt', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('keeps the worktree when the device returns an empty worktree list', async () => {+ setTopicWorktree('/tmp/wt');+ listGitWorktrees.mockResolvedValue([]);++ await recordGitCommandEffects({+ command: 'git worktree remove /tmp/wt || true',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('keeps a worktree the device lists under its canonical path', async () => {+ setTopicWorktree('/tmp/link/wt');+ listGitWorktrees.mockResolvedValue([+ { branch: 'main', path: '/repo' },+ { branch: 'fix/tab-nav', path: '/private/tmp/real/wt' },+ ]);++ await recordGitCommandEffects({+ command: 'test -f marker && git worktree remove /tmp/link/wt || true',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('keeps a Windows worktree listed with different separators and case', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree: 'C:\\Repo\\wt', isWorktree: true },+ path: 'C:\\Repo',+ },+ },+ },+ };+ listGitWorktrees.mockResolvedValue([+ { branch: 'main', path: 'C:/Repo' },+ { branch: 'wt', path: 'c:/repo/wt' },+ ]);++ await recordGitCommandEffects({+ command: 'git worktree remove C:\\Repo\\wt || true',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('matches a removal spelled differently from the recorded path', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({ command: 'git worktree remove /tmp/wt/', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });++ it('matches a Windows removal with different separators and case', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree: 'C:\\Repo\\wt', isWorktree: true },+ path: 'C:\\Repo',+ },+ },+ },+ };+ listGitWorktrees.mockResolvedValue([{ branch: 'main', path: 'C:/Repo' }]);++ await recordGitCommandEffects({ command: 'git worktree remove c:/repo/wt', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: 'C:\\Repo' },+ });+ });++ it('drops the branch and PR of a hand-picked worktree when it is removed', async () => {+ chatMocks.topics = {+ t1: {+ metadata: {+ workingDirectoryConfig: {+ git: {+ activeWorktree: '/tmp/wt',+ branch: 'feat/x',+ github: { pullRequest: { number: 7, url: 'https://github.com/o/r/pull/7' } },+ },+ path: '/repo',+ repoType: 'github',+ },+ },+ },+ };++ await recordGitCommandEffects({ command: 'git worktree remove /tmp/wt', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo', repoType: 'github' },+ });+ });++ it('records the last worktree when a command adds, removes and adds again', async () => {+ chatMocks.topics = { t1: { metadata: { workingDirectoryConfig: { path: '/repo' } } } };+ listGitWorktrees.mockResolvedValue([+ { branch: 'main', path: '/repo' },+ { branch: 'b', path: '/tmp/b' },+ ]);++ await recordGitCommandEffects({+ command:+ 'git worktree add /tmp/a -b a && git worktree remove /tmp/a && git worktree add /tmp/b -b b',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/tmp/b', branch: 'b', isWorktree: true },+ path: '/repo',+ },+ });+ });++ it('keeps the active worktree when another worktree is removed', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({ command: 'git worktree remove /tmp/other', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('ignores a command that only mentions worktree remove', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({ command: 'echo git worktree remove /tmp/wt', topicId: 't1' });++ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('keeps a worktree that the same command removes and then recreates', async () => {+ setTopicWorktree('/tmp/wt');++ await recordGitCommandEffects({+ command: 'git worktree remove /tmp/wt && git worktree add /tmp/wt -b fresh',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/tmp/wt', branch: 'fresh', isWorktree: true },+ path: '/repo',+ },+ });+ });++ it('ends on the source repo when one command adds and removes the same worktree', async () => {+ chatMocks.topics = { t1: { metadata: { workingDirectoryConfig: { path: '/repo' } } } };++ await recordGitCommandEffects({+ command: 'git worktree add /tmp/wt -b tmp && git worktree remove /tmp/wt',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: { git: { isWorktree: false }, path: '/repo' },+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex 57fba367977..797451acb25 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -1,9 +1,5 @@import { isDesktop } from '@lobechat/const';-import type {- DeviceGitLinkedPullRequest,- DeviceGitUpstreamRef,- WorkingDirConfig,-} from '@lobechat/types';+import type { DeviceGitUpstreamRef } from '@lobechat/types';import { getWorkingDirSourcePath } from '@lobechat/types';import isEqual from 'fast-deep-equal';@@ -13,6 +9,17 @@ import { getChatStoreState } from '@/store/chat/store';import { getGitStatusStoreState } from '@/store/device/gitStatus/store';import { getElectronStoreState } from '@/store/electron';+import {+ applyBranchToConfig,+ applyDetachedToConfig,+ applyPullRequestToConfig,+ applyPushToConfig,+ applyWorktreeAddToConfig,+ applyWorktreeExitToConfig,+ type PullRequestCreateInfo,+ type WorktreeAddInfo,+} from './worktreeConfigEffects';+/*** Detect git / gh side effects in a heterogeneous CLI agent's successful shell* tool call and mirror them onto the run topic's working-directory metadata.@@ -93,11 +100,6 @@ const CC_EXIT_PATTERN = /^Exited\b/;*/const CC_SESSION_ENTER_MARKER = 'The session is now working in the worktree';-interface WorktreeAddInfo {- branch?: string;- path: string;-}-interface WorktreeAddParseResult {branch?: string;/** Resolved absolute path, present only when the command yielded a trustworthy literal. */@@ -108,11 +110,6 @@ interface WorktreeAddParseResult {type BranchSwitchInfo = { branch: string } | { detached: true };-interface PullRequestCreateInfo {- branch?: string;- pullRequest: DeviceGitLinkedPullRequest;-}-const stripQuotes = (token: string): string => {if (token.length >= 2) {const first = token[0];@@ -265,6 +262,7 @@ const getOptionValue = (const parseGitSubcommand = (tokens: string[],cwd?: string,+ env?: ShellEnv,): { args: string[]; baseCwd?: string; subcommand: string } | undefined => {let i = consumeCommandPreamble(tokens);if (!isGitExecutable(tokens[i] ?? '')) return undefined;@@ -273,7 +271,7 @@ const parseGitSubcommand = (let baseCwd = cwd;while (i < tokens.length && tokens[i].startsWith('-')) {if (tokens[i] === '-C') {- const dir = stripQuotes(tokens[i + 1] ?? '');+ const dir = resolveToken(tokens[i + 1] ?? '', env);if (dir) baseCwd = resolveWorktreePath(dir, baseCwd);i += 2;} else if (GIT_VALUE_OPTS.has(tokens[i])) {@@ -535,166 +533,6 @@ const parseGitPush = (return { branch: remoteBranch, remote: push.remote ?? 'origin' };};-const applyBranchToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,- branch: string,-): WorkingDirConfig => {- const branchChanged = currentConfig?.git?.branch !== branch;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- branch,- };-- delete git.detached;- // The old branch's remote ref and PR describe a branch the topic has left. Held- // onto, `upstream` would aim the PR lookup at the wrong head — worse than none.- if (branchChanged) {- delete git.github;- delete git.upstream;- }-- return {- ...currentConfig,- git,- path: source,- ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),- };-};--const applyDetachedToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,-): WorkingDirConfig => {- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- detached: true,- };-- delete git.branch;- delete git.github;- delete git.upstream;-- return {- ...currentConfig,- git,- path: source,- ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),- };-};--const applyPullRequestToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,- info: PullRequestCreateInfo,-): WorkingDirConfig => {- const branch = info.branch ?? currentConfig?.git?.branch;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- ...(branch ? { branch } : {}),- github: {- pullRequest: info.pullRequest,- pullRequestStatus: 'ok',- },- };-- delete git.detached;-- return {- ...currentConfig,- git,- path: source,- repoType: 'github',- };-};--/**- * Record where the branch now publishes to. This is what makes the PR lookup work at- * all for a worktree: its local branch name (`worktree-feat+x`) never exists on the- * remote, so only the ref the push actually created (`feat/y`) can find the PR.- */-const applyPushToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,- upstream: DeviceGitUpstreamRef,-): WorkingDirConfig => {- const previous = currentConfig?.git?.upstream?.branch;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- upstream,- };-- // Re-pointing the branch at a DIFFERENT remote ref orphans the PR bound to the old- // one. Only a change invalidates it — a first push must not drop a PR that a- // preceding `gh pr create` in the same run just recorded.- if (previous && previous !== upstream.branch) delete git.github;-- return {- ...currentConfig,- git,- path: source,- ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),- };-};--const applyWorktreeAddToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,- info: WorktreeAddInfo,-): WorkingDirConfig => {- const branchChanged = !!info.branch && currentConfig?.git?.branch !== info.branch;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- activeWorktree: info.path,- ...(info.branch ? { branch: info.branch } : {}),- isWorktree: true,- };-- if (info.branch) delete git.detached;- if (branchChanged) {- delete git.github;- delete git.upstream;- }-- return {- ...currentConfig,- git,- path: source,- ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),- };-};--/**- * The session left the worktree and is back in the source repo. `branch`, its- * `upstream` ref 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;- delete git.upstream;- }-- 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('/');@@ -885,14 +723,16 @@ const parseWorktreeAddInfo = (const unwrapped = unwrapShellCommand(command);if (!/\bworktree\s+add\b/.test(unwrapped)) return undefined;+ // The LAST add wins: it is where the command left things, so an earlier scratch+ // worktree that was removed again (`add a && remove a && add b`) never sticks.const env: ShellEnv = {};+ let last: WorktreeAddParseResult | undefined;for (const segment of unwrapped.split(/[\n;|&]/)) {const tokens = tokenize(segment);- const info = parseGitWorktreeAddTokens(tokens, cwd, env);- if (info) return info;+ last = parseGitWorktreeAddTokens(tokens, cwd, env) ?? last;collectSegmentAssignments(tokens, env);}- return undefined;+ return last;};/**@@ -913,6 +753,62 @@ export const parseWorktreeAddPath = (return parseWorktreeAddInfo(command, cwd)?.path;};+const isWindowsPath = (p: string): boolean => /^[A-Z]:[\\/]/i.test(p) || p.startsWith('\\\\');++/** Path equality that ignores a trailing slash, and separators and case on Windows. */+const isSamePath = (a: string, b: string): boolean => {+ const normalize = (p: string) => {+ const path = p.replace(/[\\/]+$/, '');+ return isWindowsPath(p) ? path.replaceAll('\\', '/').toLowerCase() : path;+ };+ return normalize(a) === normalize(b);+};++/**+ * Whether the command's last word on `target` is a real `git worktree remove` of it.+ * Paths resolve like `add` paths; segments are read in shell order, so a later+ * `add` of the same path recreates it. Text only — the caller confirms on the+ * device, since `cond && git worktree remove …` may never have run.+ */+const removesWorktree = (command: string | string[], target: string, cwd?: string) => {+ let removed = false;+ findInCommand(command, (tokens, env) => {+ const added = parseGitWorktreeAddTokens(tokens, cwd, env)?.path;+ if (added && isSamePath(added, target)) removed = false;+ const git = parseGitSubcommand(tokens, cwd, env);+ if (git?.subcommand !== 'worktree' || stripQuotes(git.args[0] ?? '') !== 'remove') return;+ for (const token of git.args.slice(1)) {+ if (/^\d*[<>]/.test(token)) return; // redirection — git's args end here+ if (token.startsWith('-')) continue;+ const path = resolveToken(token, env);+ if (isLiteralPath(path) && isSamePath(resolveWorktreePath(path, git.baseCwd), target))+ removed = true;+ return;+ }+ });+ return removed;+};++/**+ * The source repo's worktrees as the run's device reports them; undefined when the+ * device cannot be asked. The topic's bound device (written at dispatch) or,+ * unbound, this machine — the local device answers over IPC, a remote one over RPC.+ */+const listDeviceWorktrees = async (source: string, boundDeviceId?: string) => {+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;+ const targetDeviceId = boundDeviceId ?? currentDeviceId;+ const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;++ try {+ return await gitService.listGitWorktrees({+ deviceId: isLocalDevice ? undefined : targetDeviceId,+ path: source,+ });+ } catch {+ return undefined;+ }+};+/*** Ground truth for a worktree-add whose path token never survives static parsing* (`git worktree add "$WT" …`, `$(mktemp -d)`, `~/wt`): ask the run's target@@ -928,27 +824,27 @@ const resolveWorktreeAddFromDevice = async (const branchHint = normalizeBranch(parsed.branch ?? parsed.ref);if (!branchHint) return undefined;- // The topic's bound device (written at dispatch) or, unbound, this machine.- // Mirrors WorkingDirectorySection: the local device answers over IPC- // (deviceId omitted), a remote one over RPC.- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;- const targetDeviceId = boundDeviceId ?? currentDeviceId;- const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;-- try {- const worktrees = await gitService.listGitWorktrees({- deviceId: isLocalDevice ? undefined : targetDeviceId,- path: source,- });- const match = worktrees.find((worktree) => worktree.branch === branchHint);- if (!match) return undefined;- return { ...(match.branch ? { branch: match.branch } : {}), path: match.path };- } catch {- return undefined;- }+ const match = (await listDeviceWorktrees(source, boundDeviceId))?.find(+ (worktree) => worktree.branch === branchHint,+ );+ if (!match) return undefined;+ return { ...(match.branch ? { branch: match.branch } : {}), path: match.path };};-const isWindowsPath = (p: string): boolean => /^[A-Z]:[\\/]/i.test(p) || p.startsWith('\\\\');+/**+ * Whether the device's worktree list proves `worktree` is gone. An empty list is a+ * failed probe (a repository always lists its own checkout), not a confirmation.+ * The recorded branch is matched too: git lists the canonical path, which differs+ * from the recorded one when the worktree was added through a symlink, while a+ * branch is checked out in at most one worktree.+ */+const isWorktreeGone = (+ worktrees: { branch?: string; path: string }[] | undefined,+ worktree: string,+ branch?: string,+): boolean =>+ !!worktrees?.length &&+ !worktrees.some((w) => isSamePath(w.path, worktree) || (!!branch && w.branch === branch));/*** The recorded worktree becomes the cwd of every later command on the source's@@ -1015,6 +911,7 @@ export const recordWorktreeAdd = async (params: {/*** Record successful heterogeneous CLI shell side effects onto the run topic:* - `git worktree add` selects the created worktree and explicit branch.+ * - `git worktree remove` of that worktree returns the topic to its source repo.* - `git switch` / confirmed `git checkout` updates the branch snapshot.* - `git push` records the remote ref the branch publishes to.* - `gh pr create` binds the created PR URL to the topic.@@ -1043,6 +940,17 @@ export const recordGitCommandEffects = async (params: {nextConfig = applyWorktreeAddToConfig(nextConfig, source, worktreeInfo);}+ // Removing the worktree the topic runs in leaves it pointing at a deleted+ // directory, and every later run would fail to spawn there. The device has the+ // last word: a skipped or failed removal still lists the worktree, and an+ // unreachable device changes nothing.+ const activeWorktree = nextConfig?.git?.activeWorktree;+ if (activeWorktree && removesWorktree(command, activeWorktree, source)) {+ const worktrees = await listDeviceWorktrees(source, topic?.metadata?.boundDeviceId);+ if (isWorktreeGone(worktrees, activeWorktree, nextConfig?.git?.branch))+ nextConfig = applyWorktreeExitToConfig(nextConfig, source);+ }+const branchSwitch = parseGitBranchSwitch(command, resultContent);if (branchSwitch) {nextConfig =