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.

🐛 fix(chat-input): keep git context when the recorded worktree is gone (#18476)

Arvin Xuea022d1bef4d
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index e07ace1f2e7..0a82ccda789 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -82,6 +82,9 @@
"workingDirectory.searchPlaceholder": "Search directories",
"workingDirectory.selectFolder": "Select folder",
"workingDirectory.setDefault": "Set as default",
+ "workingDirectory.staleResetToSource": "Switch back to {{name}}",
+ "workingDirectory.staleSnapshot": "The directory recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.",
+ "workingDirectory.staleWorktreeSnapshot": "The worktree “{{name}}” recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.",
"workingDirectory.title": "Working Directory",
"workingDirectory.topicDescription": "Override Agent default for this conversation only",
"workingDirectory.topicLevel": "Conversation override",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 9af9f3dc6f3..3682fc8d485 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -82,6 +82,9 @@
"workingDirectory.searchPlaceholder": "搜索工作目录",
"workingDirectory.selectFolder": "选择文件夹",
"workingDirectory.setDefault": "设为默认",
+ "workingDirectory.staleResetToSource": "切回 {{name}}",
+ "workingDirectory.staleSnapshot": "此对话记录的工作目录已不存在,展示的是话题保存的 Git 快照。",
+ "workingDirectory.staleWorktreeSnapshot": "此对话记录的工作树「{{name}}」已不存在,展示的是话题保存的 Git 快照。",
"workingDirectory.title": "工作目录",
"workingDirectory.topicDescription": "仅覆盖当前对话的工作目录",
"workingDirectory.topicLevel": "对话覆盖",
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index d97d40fdd39..3daa4e63652 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -76,6 +76,11 @@ export default {
'workingDirectory.searchPlaceholder': 'Search directories',
'workingDirectory.selectFolder': 'Select folder',
'workingDirectory.setDefault': 'Set as default',
+ 'workingDirectory.staleResetToSource': 'Switch back to {{name}}',
+ 'workingDirectory.staleSnapshot':
+ 'The directory recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.',
+ 'workingDirectory.staleWorktreeSnapshot':
+ 'The worktree “{{name}}” recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.',
'workingDirectory.title': 'Working Directory',
'workingDirectory.undo': 'Undo',
'workingDirectory.topicDescription': 'Override Agent default for this conversation only',
diff --git a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
index 7ec4347f027..15e35de59ea 100644
--- a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
+++ b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
@@ -7,7 +7,11 @@ import { cssVar } from 'antd-style';
import type { LucideIcon } from 'lucide-react';
import { GitMerge, GitPullRequestArrow, GitPullRequestClosed } from 'lucide-react';
-import { getConfigRepoType, getWorkingDirectoryName } from '@/helpers/workingDirectoryPath';
+import {
+ getConfigRepoType,
+ getWorkingDirectoryName,
+ isWorktreeCheckout,
+} from '@/helpers/workingDirectoryPath';
export type PullRequestState = 'open' | 'merged' | 'closed';
@@ -49,8 +53,7 @@ export const getTopicMetaCard = (metadata: ChatTopicMetadata | undefined) => {
const sourcePath = getTopicMetadataWorkingDirectorySourcePath(metadata);
const effectivePath = getTopicMetadataWorkingDirectoryEffectivePath(metadata);
- const isWorktree =
- !!git.isWorktree || (!!git.activeWorktree && git.activeWorktree !== sourcePath);
+ const isWorktree = isWorktreeCheckout({ effectivePath, git, sourcePath });
return {
branch: git.branch,
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index f3a16573101..cca0f3208db 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -1,3 +1,4 @@
+import type { WorkingDirGitState } from '@lobechat/types';
import { Icon, Tooltip } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
@@ -9,6 +10,8 @@ import RingLoadingIcon from '@/components/RingLoading';
import { electronSystemService } from '@/services/electron/system';
import { gitService } from '@/services/git';
import {
+ deviceSelectors,
+ useDeviceStore,
useFetchGitAheadBehind,
useFetchGitBranch,
useFetchGitLinkedPR,
@@ -19,6 +22,8 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import BranchSwitcher from './BranchSwitcher';
+import { gitChipStyles } from './gitChipStyles';
+import StaleGitSnapshot from './StaleGitSnapshot';
import WorktreeSwitcher from './WorktreeSwitcher';
const styles = createStaticStyles(({ css }) => {
@@ -68,35 +73,6 @@ const styles = createStaticStyles(({ css }) => {
diffStatModified: css`
color: ${cssVar.colorWarning};
`,
- prTrigger: css`
- cursor: pointer;
-
- display: flex;
- flex: none;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
- border-radius: 4px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- white-space: nowrap;
-
- transition: background 0.2s;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillTertiary};
- }
- `,
- separator: css`
- flex: none;
- width: 1px;
- height: 10px;
- background: ${cssVar.colorSplit};
- `,
syncTrigger: css`
cursor: pointer;
@@ -127,28 +103,6 @@ const styles = createStaticStyles(({ css }) => {
background: transparent;
}
`,
- trigger: css`
- cursor: pointer;
-
- display: flex;
- flex: none;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
- border-radius: 4px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- white-space: nowrap;
-
- transition: background 0.2s;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
};
});
@@ -157,306 +111,369 @@ interface GitStatusProps {
* remote device via RPC. Omit for the local machine (talks over IPC). */
agentId: string;
deviceId?: string;
+ /**
+ * Git context persisted on the topic, used only when the live probe finds no
+ * branch at `path` — which happens whenever the recorded worktree directory
+ * has since been deleted. Standing in for the dead probe keeps the branch /
+ * worktree / PR chips visible (read-only) instead of collapsing the whole
+ * cluster, so the bar agrees with the topic's meta hover card, which reads
+ * this same snapshot and never probes.
+ */
+ fallbackGit?: WorkingDirGitState;
isGithub: boolean;
path: string;
sourcePath?: string;
}
-const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, deviceId }) => {
- const { t } = useTranslation('device');
- // Transport (Electron IPC vs device RPC) is decided inside the service; the
- // component just reads, identically for local and remote.
- // Branch (cheap, refreshes promptly on dir switch) and the linked-PR lookup
- // (expensive `gh` call, throttled) are deliberately separate cache entries.
- const { data: branchData, mutate: mutateBranch } = useFetchGitBranch(deviceId, path);
- const branch = branchData?.branch;
- const detached = branchData?.detached;
- const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(deviceId, path, branch, isGithub);
- const { data: reviewPatches, mutate: mutateReviewPatches } = useReviewPatches(
- path,
- 'unstaged',
- undefined,
- deviceId,
- );
- const { data: aheadBehind, mutate: mutateAheadBehind } = useFetchGitAheadBehind(deviceId, path);
- const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(deviceId, path);
- const [switcherOpen, setSwitcherOpen] = useState(false);
- const [pulling, setPulling] = useState(false);
- const [pushing, setPushing] = useState(false);
- const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
- const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
- const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);
- const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);
-
- const handleOpenPr = useCallback(() => {
- if (prData?.pullRequest?.url) {
- void electronSystemService.openExternalLink(prData.pullRequest.url);
- }
- }, [prData?.pullRequest?.url]);
+const GitStatus = memo<GitStatusProps>(
+ ({ agentId, path, sourcePath, isGithub, deviceId, fallbackGit }) => {
+ const { t } = useTranslation('device');
+ // Transport (Electron IPC vs device RPC) is decided inside the service; the
+ // component just reads, identically for local and remote.
+ // Branch (cheap, refreshes promptly on dir switch) and the linked-PR lookup
+ // (expensive `gh` call, throttled) are deliberately separate cache entries.
+ const {
+ data: branchData,
+ error: branchError,
+ mutate: mutateBranch,
+ } = useFetchGitBranch(deviceId, path);
+ const branch = branchData?.branch;
+ const detached = branchData?.detached;
+ // The persisted snapshot only stands in once the probe has actually ANSWERED.
+ // `getGitBranch` resolves to `{}` for a path it can't read, so a settled probe
+ // is `data !== undefined` (or an errored one) — keying off `!branch` alone
+ // would flash the snapshot cluster on every mount while loading.
+ const probeSettled = branchData !== undefined || !!branchError;
+ // …and only when the probe could reach the directory at all. A remote read
+ // whose device is offline (or whose RPC failed) comes back `undefined`, which
+ // the service normalizes into the SAME empty shape a deleted path produces —
+ // so an unreachable device would otherwise be reported as a missing directory,
+ // offering to drop a worktree override that is perfectly alive. A local read
+ // talks to this filesystem directly and has no such ambiguity.
+ const deviceOnline = useDeviceStore(
+ (s) => !!deviceSelectors.getDeviceById(deviceId)(s)?.online,
+ );
+ const probeReachedDirectory = !deviceId || deviceOnline;
+ const isStale = !branch && probeSettled && probeReachedDirectory && !!fallbackGit?.branch;
+ const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(
+ deviceId,
+ path,
+ branch,
+ isGithub,
+ );
+ // The remaining reads are all disabled once the directory is gone: nothing
+ // below renders from them in that state, and the diff poll alone would keep
+ // shelling out to git every 10s — one RPC round-trip per tick on a remote
+ // device — against a path we already know cannot be read.
+ const { data: reviewPatches, mutate: mutateReviewPatches } = useReviewPatches(
+ path,
+ 'unstaged',
+ undefined,
+ deviceId,
+ !isStale,
+ );
+ const livePath = isStale ? undefined : path;
+ const { data: aheadBehind, mutate: mutateAheadBehind } = useFetchGitAheadBehind(
+ deviceId,
+ livePath,
+ );
+ const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(
+ deviceId,
+ livePath,
+ );
+ const [switcherOpen, setSwitcherOpen] = useState(false);
+ const [pulling, setPulling] = useState(false);
+ const [pushing, setPushing] = useState(false);
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
+ const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);
+ const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);
+
+ const handleOpenPr = useCallback(() => {
+ if (prData?.pullRequest?.url) {
+ void electronSystemService.openExternalLink(prData.pullRequest.url);
+ }
+ }, [prData?.pullRequest?.url]);
- const handleToggleReview = useCallback(() => {
- if (showRightPanel && workingSidebarTab === 'review') {
- toggleRightPanel(false);
- return;
- }
- setWorkingSidebarTab('review');
- toggleRightPanel(true);
- }, [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel]);
-
- const refreshAfterSync = useCallback(async () => {
- await Promise.all([
- mutateBranch(),
- mutatePR(),
- mutateReviewPatches(),
- mutateAheadBehind(),
- mutateWorktrees(),
- ]);
- }, [mutateBranch, mutatePR, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);
-
- // Flip the displayed branch instantly on checkout. No revalidate here — the
- // switcher's onAfterCheckout reconciles once the checkout lands. The linked-PR
- // hook is keyed by branch, so it re-keys to the new branch on its own (its
- // cache starts empty there, hiding the stale PR until the lookup resolves).
- const handleOptimisticCheckout = useCallback(
- (nextBranch: string) => {
- void mutateBranch({ branch: nextBranch, detached: false }, { revalidate: false });
- },
- [mutateBranch],
- );
-
- const syncBusy = pulling || pushing;
-
- const handlePull = useCallback(async () => {
- if (pulling || pushing) return;
- setPulling(true);
- try {
- const result = await gitService.pullGitBranch({ deviceId, path });
- if (result.success) {
- if (result.noop) {
- toast.info(t('workingDirectory.pullNoop'));
+ const handleToggleReview = useCallback(() => {
+ if (showRightPanel && workingSidebarTab === 'review') {
+ toggleRightPanel(false);
+ return;
+ }
+ setWorkingSidebarTab('review');
+ toggleRightPanel(true);
+ }, [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel]);
+
+ const refreshAfterSync = useCallback(async () => {
+ await Promise.all([
+ mutateBranch(),
+ mutatePR(),
+ mutateReviewPatches(),
+ mutateAheadBehind(),
+ mutateWorktrees(),
+ ]);
+ }, [mutateBranch, mutatePR, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);
+
+ // Flip the displayed branch instantly on checkout. No revalidate here — the
+ // switcher's onAfterCheckout reconciles once the checkout lands. The linked-PR
+ // hook is keyed by branch, so it re-keys to the new branch on its own (its
+ // cache starts empty there, hiding the stale PR until the lookup resolves).
+ const handleOptimisticCheckout = useCallback(
+ (nextBranch: string) => {
+ void mutateBranch({ branch: nextBranch, detached: false }, { revalidate: false });
+ },
+ [mutateBranch],
+ );
+
+ const syncBusy = pulling || pushing;
+
+ const handlePull = useCallback(async () => {
+ if (pulling || pushing) return;
+ setPulling(true);
+ try {
+ const result = await gitService.pullGitBranch({ deviceId, path });
+ if (result.success) {
+ if (result.noop) {
+ toast.info(t('workingDirectory.pullNoop'));
+ } else {
+ toast.success(t('workingDirectory.pullSuccess'));
+ }
+ await refreshAfterSync();
} else {
- toast.success(t('workingDirectory.pullSuccess'));
+ toast.error(result.error || t('workingDirectory.pullFailed'));
}
- await refreshAfterSync();
- } else {
- toast.error(result.error || t('workingDirectory.pullFailed'));
+ } finally {
+ setPulling(false);
}
- } finally {
- setPulling(false);
- }
- }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
-
- const handlePush = useCallback(async () => {
- if (pulling || pushing) return;
- setPushing(true);
- try {
- const result = await gitService.pushGitBranch({ deviceId, path });
- if (result.success) {
- if (result.noop) {
- toast.info(t('workingDirectory.pushNoop'));
+ }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
+
+ const handlePush = useCallback(async () => {
+ if (pulling || pushing) return;
+ setPushing(true);
+ try {
+ const result = await gitService.pushGitBranch({ deviceId, path });
+ if (result.success) {
+ if (result.noop) {
+ toast.info(t('workingDirectory.pushNoop'));
+ } else {
+ toast.success(t('workingDirectory.pushSuccess'));
+ }
+ await refreshAfterSync();
} else {
- toast.success(t('workingDirectory.pushSuccess'));
+ toast.error(result.error || t('workingDirectory.pushFailed'));
}
- await refreshAfterSync();
- } else {
- toast.error(result.error || t('workingDirectory.pushFailed'));
+ } finally {
+ setPushing(false);
}
- } finally {
- setPushing(false);
+ }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
+
+ const diffStats = useMemo(() => {
+ const patches = [
+ ...(reviewPatches?.patches ?? []),
+ ...(reviewPatches?.submodules ?? []).flatMap((submodule) => submodule.patches),
+ ];
+ return patches.reduce(
+ (acc, patch) => {
+ acc.additions += patch.additions ?? 0;
+ acc.deletions += patch.deletions ?? 0;
+ acc.files += 1;
+ return acc;
+ },
+ { additions: 0, deletions: 0, files: 0 },
+ );
+ }, [reviewPatches?.patches, reviewPatches?.submodules]);
+ const hasChanges = diffStats.files > 0;
+
+ // Dead directory: the whole live cluster is unreachable, so hand off to the
+ // snapshot renderer — it shows what the topic recorded and offers the one
+ // action that can still work (drop the worktree override).
+ if (isStale) {
+ return (
+ <StaleGitSnapshot
+ agentId={agentId}
+ git={fallbackGit!}
+ isGithub={isGithub}
+ path={path}
+ sourcePath={sourcePath}
+ />
+ );
}
- }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
-
- const diffStats = useMemo(() => {
- const patches = [
- ...(reviewPatches?.patches ?? []),
- ...(reviewPatches?.submodules ?? []).flatMap((submodule) => submodule.patches),
- ];
- return patches.reduce(
- (acc, patch) => {
- acc.additions += patch.additions ?? 0;
- acc.deletions += patch.deletions ?? 0;
- acc.files += 1;
- return acc;
- },
- { additions: 0, deletions: 0, files: 0 },
- );
- }, [reviewPatches?.patches, reviewPatches?.submodules]);
- const hasChanges = diffStats.files > 0;
- if (!branch) return null;
-
- const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;
-
- const prTooltip = prData?.pullRequest
- ? prData.extraCount
- ? t('workingDirectory.prTooltipWithExtra', {
- count: prData.extraCount,
- title: prData.pullRequest.title,
+ if (!branch) return null;
+
+ const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;
+
+ const prTooltip = prData?.pullRequest
+ ? prData.extraCount
+ ? t('workingDirectory.prTooltipWithExtra', {
+ count: prData.extraCount,
+ title: prData.pullRequest.title,
+ })
+ : prData.pullRequest.title
+ : prData?.ghMissing
+ ? t('workingDirectory.ghMissing')
+ : undefined;
+
+ const diffStatTooltip = hasChanges
+ ? t('workingDirectory.diffLineStatTooltip', {
+ added: diffStats.additions,
+ deleted: diffStats.deletions,
+ files: diffStats.files,
})
- : prData.pullRequest.title
- : prData?.ghMissing
- ? t('workingDirectory.ghMissing')
: undefined;
- const diffStatTooltip = hasChanges
- ? t('workingDirectory.diffLineStatTooltip', {
- added: diffStats.additions,
- deleted: diffStats.deletions,
- files: diffStats.files,
- })
- : undefined;
-
- const showAhead = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.ahead > 0;
- const showBehind = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.behind > 0;
- const upstreamName = aheadBehind?.upstream ?? '';
- const pushTargetName = aheadBehind?.pushTarget ?? '';
- const pushTargetExists = !!aheadBehind?.pushTargetExists;
-
- const branchTrigger = (
- <div className={styles.trigger}>
- <span className={styles.branchLabel}>{branch}</span>
- </div>
- );
-
- const hasWorktreeMenu = worktrees.length > 0;
-
- const worktreeNode = hasWorktreeMenu ? (
- <WorktreeSwitcher
- agentId={agentId}
- currentBranch={branch}
- detached={detached}
- deviceId={deviceId}
- isGithub={isGithub}
- path={path}
- sourcePath={sourcePath ?? path}
- worktrees={worktrees}
- onWorktreesChange={mutateWorktrees}
- />
- ) : null;
-
- const branchNode = detached ? (
- // Detached HEAD → plain branch label (nothing to switch to).
- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
- ) : (
- // Local switches over IPC; a remote device switches over RPC (deviceId set).
- <BranchSwitcher
- agentId={agentId}
- currentBranch={branch}
- deviceId={deviceId}
- isGithub={isGithub}
- open={switcherOpen}
- path={path}
- sourcePath={sourcePath ?? path}
- worktrees={worktrees}
- onExternalRefresh={refreshAfterSync}
- onOpenChange={setSwitcherOpen}
- onOptimisticCheckout={handleOptimisticCheckout}
- onAfterCheckout={() => {
- void mutateBranch();
- void mutatePR();
- void mutateReviewPatches();
- void mutateAheadBehind();
- void mutateWorktrees();
- }}
- >
- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
- </BranchSwitcher>
- );
-
- const pullTooltip = pulling
- ? t('workingDirectory.pullInProgress')
- : t('workingDirectory.pullAction', {
- count: aheadBehind?.behind ?? 0,
- upstream: upstreamName,
- });
-
- const pushTooltip = pushing
- ? t('workingDirectory.pushInProgress')
- : t(pushTargetExists ? 'workingDirectory.pushAction' : 'workingDirectory.pushActionNew', {
- count: aheadBehind?.ahead ?? 0,
- target: pushTargetName || upstreamName,
- });
-
- const pullNode = showBehind && (
- <Tooltip title={pullTooltip}>
- <div
- aria-busy={pulling}
- aria-disabled={syncBusy}
- className={`${styles.syncTrigger} ${styles.behindStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
- role="button"
- onClick={syncBusy ? undefined : handlePull}
- >
- <span className={styles.aheadBehindStat}>
- {pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}
- {aheadBehind!.behind}
- </span>
+ const showAhead = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.ahead > 0;
+ const showBehind = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.behind > 0;
+ const upstreamName = aheadBehind?.upstream ?? '';
+ const pushTargetName = aheadBehind?.pushTarget ?? '';
+ const pushTargetExists = !!aheadBehind?.pushTargetExists;
+
+ const branchTrigger = (
+ <div className={gitChipStyles.trigger}>
+ <span className={styles.branchLabel}>{branch}</span>
</div>
- </Tooltip>
- );
-
- const pushNode = showAhead && (
- <Tooltip title={pushTooltip}>
- <div
- aria-busy={pushing}
- aria-disabled={syncBusy}
- className={`${styles.syncTrigger} ${styles.aheadStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
- role="button"
- onClick={syncBusy ? undefined : handlePush}
+ );
+
+ const hasWorktreeMenu = worktrees.length > 0;
+
+ const worktreeNode = hasWorktreeMenu ? (
+ <WorktreeSwitcher
+ agentId={agentId}
+ currentBranch={branch}
+ detached={detached}
+ deviceId={deviceId}
+ isGithub={isGithub}
+ path={path}
+ sourcePath={sourcePath ?? path}
+ worktrees={worktrees}
+ onWorktreesChange={mutateWorktrees}
+ />
+ ) : null;
+
+ const branchNode = detached ? (
+ // Detached HEAD → plain branch label (nothing to switch to).
+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
+ ) : (
+ // Local switches over IPC; a remote device switches over RPC (deviceId set).
+ <BranchSwitcher
+ agentId={agentId}
+ currentBranch={branch}
+ deviceId={deviceId}
+ isGithub={isGithub}
+ open={switcherOpen}
+ path={path}
+ sourcePath={sourcePath ?? path}
+ worktrees={worktrees}
+ onExternalRefresh={refreshAfterSync}
+ onOpenChange={setSwitcherOpen}
+ onOptimisticCheckout={handleOptimisticCheckout}
+ onAfterCheckout={() => {
+ void mutateBranch();
+ void mutatePR();
+ void mutateReviewPatches();
+ void mutateAheadBehind();
+ void mutateWorktrees();
+ }}
>
- <span className={styles.aheadBehindStat}>
- {pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}
- {aheadBehind!.ahead}
- </span>
- </div>
- </Tooltip>
- );
-
- const diffNode = (() => {
- if (!hasChanges) return null;
- const diffButton = (
- <div className={styles.trigger} role="button" onClick={handleToggleReview}>
- <span className={styles.diffStat}>
- {diffStats.additions > 0 && (
- <span className={styles.diffStatAdded}>+{diffStats.additions}</span>
- )}
- {diffStats.deletions > 0 && (
- <span className={styles.diffStatDeleted}>-{diffStats.deletions}</span>
- )}
- {diffStats.additions === 0 && diffStats.deletions === 0 && diffStats.files > 0 && (
- <span className={styles.diffStatModified}>±{diffStats.files}</span>
- )}
- </span>
- </div>
+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
+ </BranchSwitcher>
);
- return <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>;
- })();
-
- return (
- <>
- <div className={styles.separator} />
- {/* The worktree icon and the branch name name one thing — which checkout
- * you're on — so they sit closer to each other than to their neighbours. */}
- <div className={styles.branchGroup}>
- {worktreeNode}
- {branchNode}
- </div>
- {pullNode}
- {pushNode}
- {diffNode}
- {prData?.pullRequest && (
- <>
- <div className={styles.separator} />
- <Tooltip title={prTooltip}>
- <div className={styles.prTrigger} role="button" onClick={handleOpenPr}>
- <Icon icon={GitPullRequest} size={12} />
- <span>#{prData.pullRequest.number}</span>
- </div>
- </Tooltip>
- </>
- )}
- </>
- );
-});
+
+ const pullTooltip = pulling
+ ? t('workingDirectory.pullInProgress')
+ : t('workingDirectory.pullAction', {
+ count: aheadBehind?.behind ?? 0,
+ upstream: upstreamName,
+ });
+
+ const pushTooltip = pushing
+ ? t('workingDirectory.pushInProgress')
+ : t(pushTargetExists ? 'workingDirectory.pushAction' : 'workingDirectory.pushActionNew', {
+ count: aheadBehind?.ahead ?? 0,
+ target: pushTargetName || upstreamName,
+ });
+
+ const pullNode = showBehind && (
+ <Tooltip title={pullTooltip}>
+ <div
+ aria-busy={pulling}
+ aria-disabled={syncBusy}
+ className={`${styles.syncTrigger} ${styles.behindStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ role="button"
+ onClick={syncBusy ? undefined : handlePull}
+ >
+ <span className={styles.aheadBehindStat}>
+ {pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}
+ {aheadBehind!.behind}
+ </span>
+ </div>
+ </Tooltip>
+ );
+
+ const pushNode = showAhead && (
+ <Tooltip title={pushTooltip}>
+ <div
+ aria-busy={pushing}
+ aria-disabled={syncBusy}
+ className={`${styles.syncTrigger} ${styles.aheadStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ role="button"
+ onClick={syncBusy ? undefined : handlePush}
+ >
+ <span className={styles.aheadBehindStat}>
+ {pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}
+ {aheadBehind!.ahead}
+ </span>
+ </div>
+ </Tooltip>
+ );
+
+ const diffNode = (() => {
+ if (!hasChanges) return null;
+ const diffButton = (
+ <div className={gitChipStyles.trigger} role="button" onClick={handleToggleReview}>
+ <span className={styles.diffStat}>
+ {diffStats.additions > 0 && (
+ <span className={styles.diffStatAdded}>+{diffStats.additions}</span>
+ )}
+ {diffStats.deletions > 0 && (
+ <span className={styles.diffStatDeleted}>-{diffStats.deletions}</span>
+ )}
+ {diffStats.additions === 0 && diffStats.deletions === 0 && diffStats.files > 0 && (
+ <span className={styles.diffStatModified}>±{diffStats.files}</span>
+ )}
+ </span>
+ </div>
+ );
+ return <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>;
+ })();
+
+ return (
+ <>
+ <div className={gitChipStyles.separator} />
+ {/* The worktree icon and the branch name name one thing — which checkout
+ * you're on — so they sit closer to each other than to their neighbours. */}
+ <div className={styles.branchGroup}>
+ {worktreeNode}
+ {branchNode}
+ </div>
+ {pullNode}
+ {pushNode}
+ {diffNode}
+ {prData?.pullRequest && (
+ <>
+ <div className={gitChipStyles.separator} />
+ <Tooltip title={prTooltip}>
+ <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>
+ <Icon icon={GitPullRequest} size={12} />
+ <span>#{prData.pullRequest.number}</span>
+ </div>
+ </Tooltip>
+ </>
+ )}
+ </>
+ );
+ },
+);
GitStatus.displayName = 'GitStatus';
diff --git a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
new file mode 100644
index 00000000000..cef9ded4ab9
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
@@ -0,0 +1,161 @@
+import type { WorkingDirGitState } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import {
+ DropdownMenuItem,
+ DropdownMenuPopup,
+ DropdownMenuPortal,
+ DropdownMenuPositioner,
+ DropdownMenuRoot,
+ DropdownMenuTrigger,
+} from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { GitBranchIcon, GitForkIcon, GitPullRequest, RotateCcwIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { gitChipStyles } from './gitChipStyles';
+import { resolveStaleSnapshot } from './staleSnapshot';
+import { useSwitchWorktree } from './useSwitchWorktree';
+
+const styles = createStaticStyles(({ css }) => ({
+ action: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ `,
+ explanation: css`
+ max-width: 320px;
+ padding-block: 6px 8px;
+ padding-inline: 10px;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ path: css`
+ display: block;
+
+ margin-block-start: 2px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ color: ${cssVar.colorTextTertiary};
+ word-break: break-all;
+ `,
+ popup: css`
+ padding: 0;
+ `,
+ triggerLabel: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+interface StaleGitSnapshotProps {
+ agentId: string;
+ /** The topic's persisted git context — the only source here; nothing is probed. */
+ git: WorkingDirGitState;
+ isGithub: boolean;
+ /** The recorded effective directory, i.e. the one that no longer exists. */
+ path: string;
+ /** The source repo the worktree was linked from, when the topic recorded one. */
+ sourcePath?: string;
+}
+
+/**
+ * What the control bar shows when the directory the topic recorded is gone.
+ *
+ * Every live control (checkout, worktree switch, pull/push, diff review) needs a
+ * directory that no longer exists, so none of them render. What remains is the
+ * topic's own snapshot — the same one the sidebar meta hover card reads — plus
+ * the two things that still work without a local directory: opening the linked
+ * PR, and dropping the dead worktree override so the conversation falls back to
+ * its source repo. Without that second one the state is a dead end: the bar
+ * explains why the branch is frozen but leaves no way out of it.
+ */
+const StaleGitSnapshot = memo<StaleGitSnapshotProps>(
+ ({ agentId, git, isGithub, path, sourcePath }) => {
+ const { t } = useTranslation('device');
+ const [open, setOpen] = useState(false);
+ const [resetting, setResetting] = useState(false);
+ const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath: sourcePath ?? path });
+
+ const { branch, explanation, isWorktree, pullRequest, reset, worktreePath } =
+ resolveStaleSnapshot({ git, path, sourcePath });
+
+ const handleOpenPr = useCallback(() => {
+ if (pullRequest?.url) {
+ void electronSystemService.openExternalLink(pullRequest.url);
+ }
+ }, [pullRequest?.url]);
+
+ const resetTarget = reset?.targetPath;
+ const handleReset = useCallback(async () => {
+ if (resetting || !resetTarget) return;
+ setResetting(true);
+ try {
+ // Committing the SOURCE path is what clears `git.activeWorktree` — same
+ // funnel the worktree dropdown uses, so the two can't drift apart.
+ await switchWorktree(resetTarget);
+ setOpen(false);
+ } finally {
+ setResetting(false);
+ }
+ }, [resetting, resetTarget, switchWorktree]);
+
+ const trigger = (
+ <div className={gitChipStyles.staleTrigger}>
+ <Icon icon={isWorktree ? GitForkIcon : GitBranchIcon} size={12} />
+ <span className={styles.triggerLabel}>{branch}</span>
+ </div>
+ );
+
+ return (
+ <>
+ <div className={gitChipStyles.separator} />
+ <DropdownMenuRoot open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger>
+ <div>{trigger}</div>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuPositioner placement="topLeft" sideOffset={8}>
+ <DropdownMenuPopup className={styles.popup}>
+ <div className={styles.explanation}>
+ {t(explanation.key, explanation.values)}
+ <span className={styles.path}>{worktreePath}</span>
+ </div>
+ {reset && (
+ <DropdownMenuItem
+ aria-disabled={resetting}
+ closeOnClick={false}
+ onClick={handleReset}
+ >
+ <div className={styles.action}>
+ <Icon icon={RotateCcwIcon} size={14} />
+ <span>{t('workingDirectory.staleResetToSource', { name: reset.name })}</span>
+ </div>
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ {pullRequest && (
+ <>
+ <div className={gitChipStyles.separator} />
+ <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>
+ <Icon icon={GitPullRequest} size={12} />
+ <span>#{pullRequest.number}</span>
+ </div>
+ </>
+ )}
+ </>
+ );
+ },
+);
+
+StaleGitSnapshot.displayName = 'StaleGitSnapshot';
+
+export default StaleGitSnapshot;
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index 8f1864da0c6..0b3f52b345f 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -52,7 +52,10 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
// path that was never registered as a device working dir — so fall back to the
// repoType persisted on the topic (the same snapshot the meta hover card reads).
// Without this the whole GitStatus is gated out and branch/worktree/PR chips
- // vanish even though the topic clearly carries git context.
+ // vanish even though the topic clearly carries git context. The same snapshot
+ // also feeds GitStatus's `fallbackGit`, which covers the harder case: the
+ // recorded worktree directory was DELETED, so the live branch probe reads
+ // nothing and the chips would vanish even with repoType resolved.
const topicWorkingDirectoryConfig = useChatStore(
(s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,
);
@@ -96,6 +99,7 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
<GitStatus
agentId={agentId}
deviceId={isLocalDevice ? undefined : targetDeviceId}
+ fallbackGit={persistedConfig?.git}
isGithub={repoType === 'github'}
path={effectiveWorkingDirectory}
sourcePath={sourceWorkingDirectory}
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 4febadc9cb1..841cc5cb4c6 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -13,6 +13,10 @@ const globalStoreMock = vi.hoisted(() => ({
toggleRightPanel: vi.fn(),
}));
+const deviceStoreMock = vi.hoisted(() => ({
+ devices: [] as { deviceId: string; online: boolean }[],
+}));
+
const gitHookMocks = vi.hoisted(() => ({
mutateAheadBehind: vi.fn(),
mutateBranch: vi.fn(),
@@ -34,7 +38,19 @@ vi.mock('../WorktreeSwitcher', () => ({
default: () => <span data-testid="worktree-switcher" />,
}));
+vi.mock('../StaleGitSnapshot', () => ({
+ default: ({ git }: { git: { branch?: string } }) => (
+ <span data-branch={git.branch} data-testid="stale-git-snapshot" />
+ ),
+}));
+
vi.mock('@/store/device', () => ({
+ deviceSelectors: {
+ getDeviceById: (deviceId?: string) => (state: typeof deviceStoreMock) =>
+ state.devices.find((d) => d.deviceId === deviceId),
+ },
+ useDeviceStore: (selector: (state: typeof deviceStoreMock) => unknown) =>
+ selector(deviceStoreMock),
useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,
useFetchGitBranch: gitHookMocks.useFetchGitBranch,
useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,
@@ -97,6 +113,7 @@ vi.mock('react-i18next', () => ({
beforeEach(() => {
vi.clearAllMocks();
+ deviceStoreMock.devices = [{ deviceId: 'device-1', online: true }];
globalStoreMock.status.showRightPanel = false;
globalStoreMock.status.workingSidebarTab = 'resources';
@@ -144,6 +161,7 @@ describe('GitStatus', () => {
'unstaged',
undefined,
'device-1',
+ true,
);
expect(screen.getByText('+3')).toBeInTheDocument();
expect(screen.getByText('-1')).toBeInTheDocument();
@@ -180,6 +198,153 @@ describe('GitStatus', () => {
});
});
+ describe('deleted working directory', () => {
+ // The recorded worktree gets removed once its task is done, but the topic
+ // keeps pointing at it — the live branch probe then reads nothing and the
+ // whole cluster used to collapse, while the sidebar hover card (which reads
+ // the same persisted snapshot, no probe) still showed branch + PR.
+ const fallbackGit = {
+ activeWorktree: '/tmp/lobehub-wt-subtask',
+ branch: 'feat/task-list-subtask-nesting',
+ isWorktree: true,
+ };
+
+ beforeEach(() => {
+ // `getGitBranch` resolves to `{}` for a path it can't read — a SETTLED
+ // probe that found no branch, not a pending one.
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: {},
+ mutate: gitHookMocks.mutateBranch,
+ });
+ });
+
+ it('hands off to the topic snapshot instead of collapsing', () => {
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ sourcePath="/repo"
+ />,
+ );
+
+ expect(screen.getByTestId('stale-git-snapshot')).toHaveAttribute(
+ 'data-branch',
+ 'feat/task-list-subtask-nesting',
+ );
+ expect(screen.queryByTestId('worktree-switcher')).not.toBeInTheDocument();
+ });
+
+ it('skips the linked-PR lookup, which has no directory to run `gh` in', () => {
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ />,
+ );
+
+ expect(gitHookMocks.useFetchGitLinkedPR).toHaveBeenCalledWith(
+ undefined,
+ '/tmp/lobehub-wt-subtask',
+ undefined,
+ true,
+ );
+ });
+
+ it('stays empty while the probe is still pending, so no stale flash', () => {
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutateBranch,
+ });
+
+ const { container } = render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders nothing when the topic carries no git snapshot either', () => {
+ const { container } = render(
+ <GitStatus isGithub agentId="agent-1" path="/tmp/lobehub-wt-subtask" />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('stops probing the directory it just declared gone', () => {
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ />,
+ );
+
+ // Left enabled, the diff poll alone keeps shelling out to git every 10s
+ // against a path that cannot be read.
+ expect(gitHookMocks.useReviewPatches).toHaveBeenCalledWith(
+ '/tmp/lobehub-wt-subtask',
+ 'unstaged',
+ undefined,
+ undefined,
+ false,
+ );
+ expect(gitHookMocks.useFetchGitAheadBehind).toHaveBeenCalledWith(undefined, undefined);
+ expect(gitHookMocks.useFetchGitWorktrees).toHaveBeenCalledWith(undefined, undefined);
+ });
+
+ // A remote device that is offline answers `undefined`, which the service
+ // normalizes into the same empty shape a deleted directory produces. Reading
+ // that as "gone" would tell the user a live worktree no longer exists — and
+ // offer to drop the override pointing at it.
+ it('does not read an unreachable device as a deleted directory', () => {
+ deviceStoreMock.devices = [{ deviceId: 'device-1', online: false }];
+
+ const { container } = render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ deviceId="device-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ // …and the reads stay enabled, so the cluster comes back on reconnect.
+ expect(gitHookMocks.useFetchGitWorktrees).toHaveBeenCalledWith(
+ 'device-1',
+ '/tmp/lobehub-wt-subtask',
+ );
+ });
+
+ it('hands off once that same device is reachable again', () => {
+ deviceStoreMock.devices = [{ deviceId: 'device-1', online: true }];
+
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ deviceId="device-1"
+ fallbackGit={fallbackGit}
+ path="/tmp/lobehub-wt-subtask"
+ />,
+ );
+
+ expect(screen.getByTestId('stale-git-snapshot')).toBeInTheDocument();
+ });
+ });
+
it('keeps branch switching visible when worktrees are available', () => {
gitHookMocks.useFetchGitWorktrees.mockReturnValue({
data: [
diff --git a/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts b/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts
new file mode 100644
index 00000000000..41ce08033ab
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveStaleSnapshot } from '../staleSnapshot';
+
+// The recorded worktree gets deleted once its task is done, but the topic keeps
+// pointing at it. The live git probe then reads nothing, so everything the bar
+// can still show comes from this snapshot — including the way out of it.
+const deadWorktree = {
+ activeWorktree: '/tmp/lobehub-wt-subtask',
+ branch: 'feat/task-list-subtask-nesting',
+ github: {
+ pullRequest: {
+ number: 18_454,
+ state: 'OPEN',
+ title: 'PR #18454',
+ url: 'https://github.com/lobehub/lobehub/pull/18454',
+ },
+ pullRequestStatus: 'ok' as const,
+ },
+ isWorktree: true,
+};
+
+describe('resolveStaleSnapshot', () => {
+ it('surfaces the recorded branch, worktree and linked PR', () => {
+ const view = resolveStaleSnapshot({ git: deadWorktree, path: '/tmp/lobehub-wt-subtask' });
+
+ expect(view.branch).toBe('feat/task-list-subtask-nesting');
+ expect(view.worktreePath).toBe('/tmp/lobehub-wt-subtask');
+ expect(view.isWorktree).toBe(true);
+ expect(view.pullRequest?.number).toBe(18_454);
+ });
+
+ it('names the missing worktree in the explanation', () => {
+ const view = resolveStaleSnapshot({ git: deadWorktree, path: '/tmp/lobehub-wt-subtask' });
+
+ expect(view.explanation).toEqual({
+ key: 'workingDirectory.staleWorktreeSnapshot',
+ values: { name: 'lobehub-wt-subtask' },
+ });
+ });
+
+ it('offers a way back to the source repo, named after it', () => {
+ const view = resolveStaleSnapshot({
+ git: deadWorktree,
+ path: '/tmp/lobehub-wt-subtask',
+ sourcePath: '/Users/me/code/lobehub',
+ });
+
+ // Committing the source path is what drops `git.activeWorktree`, so the
+ // target must be the repo root itself — not the dead checkout.
+ expect(view.reset).toEqual({ name: 'lobehub', targetPath: '/Users/me/code/lobehub' });
+ });
+
+ it('offers no way back when the recorded source repo is itself the dead path', () => {
+ const view = resolveStaleSnapshot({
+ git: { branch: 'canary' },
+ path: '/Users/me/code/gone',
+ sourcePath: '/Users/me/code/gone',
+ });
+
+ // Nothing to fall back to: dropping the override would land on the same
+ // missing directory, so recovery belongs to the directory picker.
+ expect(view.reset).toBeUndefined();
+ expect(view.explanation).toEqual({ key: 'workingDirectory.staleSnapshot' });
+ expect(view.isWorktree).toBe(false);
+ });
+
+ it('treats a checkout that differs from the source as a worktree even without the flag', () => {
+ // Older topics were persisted before `isWorktree` existed; the paths still
+ // tell us it was a linked checkout.
+ const view = resolveStaleSnapshot({
+ git: { activeWorktree: '/tmp/wt-legacy', branch: 'fix/x' },
+ path: '/tmp/wt-legacy',
+ sourcePath: '/Users/me/code/lobehub',
+ });
+
+ expect(view.isWorktree).toBe(true);
+ expect(view.explanation.values).toEqual({ name: 'wt-legacy' });
+ expect(view.reset?.targetPath).toBe('/Users/me/code/lobehub');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/gitChipStyles.ts b/src/features/ChatInput/ControlBar/gitChipStyles.ts
new file mode 100644
index 00000000000..5b5796de760
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/gitChipStyles.ts
@@ -0,0 +1,87 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+/**
+ * Chips shared by the live git status and by the snapshot that stands in for it
+ * once the recorded directory is gone. Both render into the same composer bar,
+ * so the separator and the PR chip must be pixel-identical — and `staleTrigger`,
+ * the deliberately muted variant of `trigger`, lives next to the live one so the
+ * two can't drift apart.
+ */
+export const gitChipStyles = createStaticStyles(({ css }) => ({
+ prTrigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ transition: background 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ separator: css`
+ flex: none;
+ width: 1px;
+ height: 10px;
+ background: ${cssVar.colorSplit};
+ `,
+ // Muted so the snapshot never reads as live state, but still a control: the
+ // recovery action is the only thing this cluster can still do.
+ staleTrigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 4px;
+ align-items: center;
+
+ max-width: 200px;
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ white-space: nowrap;
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
diff --git a/src/features/ChatInput/ControlBar/staleSnapshot.ts b/src/features/ChatInput/ControlBar/staleSnapshot.ts
new file mode 100644
index 00000000000..5b6b2f5e4cd
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/staleSnapshot.ts
@@ -0,0 +1,65 @@
+import type { DeviceGitLinkedPullRequest, WorkingDirGitState } from '@lobechat/types';
+
+import { getWorkingDirectoryName, isWorktreeCheckout } from '@/helpers/workingDirectoryPath';
+
+export type StaleSnapshotExplanationKey =
+ 'workingDirectory.staleSnapshot' | 'workingDirectory.staleWorktreeSnapshot';
+
+export interface StaleSnapshotView {
+ /** The branch the topic recorded — the snapshot's headline. */
+ branch?: string;
+ explanation: {
+ key: StaleSnapshotExplanationKey;
+ values?: { name: string };
+ };
+ /** True when the recorded checkout was a linked worktree, not the repo itself. */
+ isWorktree: boolean;
+ pullRequest?: DeviceGitLinkedPullRequest;
+ /**
+ * Where "go back" lands, and whether it is offered at all. Present only when a
+ * worktree override can be dropped — if the recorded SOURCE repo is itself the
+ * dead path there is nothing to fall back to, and recovery belongs to the
+ * directory picker instead.
+ */
+ reset?: { name?: string; targetPath: string };
+ /** The recorded directory that no longer exists. */
+ worktreePath: string;
+}
+
+interface ResolveStaleSnapshotParams {
+ git: WorkingDirGitState;
+ /** The recorded effective directory, i.e. the one that no longer exists. */
+ path: string;
+ /** The source repo the worktree was linked from, when the topic recorded one. */
+ sourcePath?: string;
+}
+
+/**
+ * What the control bar can still say and do once the directory a topic recorded
+ * has been deleted. Split from the component so the decisions — which
+ * explanation applies, and whether a way back exists — are testable without
+ * rendering a dropdown.
+ */
+export const resolveStaleSnapshot = ({
+ git,
+ path,
+ sourcePath,
+}: ResolveStaleSnapshotParams): StaleSnapshotView => {
+ const worktreePath = git.activeWorktree || path;
+ const isWorktree = isWorktreeCheckout({ effectivePath: worktreePath, git, sourcePath });
+ const worktreeName = isWorktree ? getWorkingDirectoryName(worktreePath) : undefined;
+ const canReset = !!sourcePath && worktreePath !== sourcePath;
+
+ return {
+ branch: git.branch,
+ explanation: worktreeName
+ ? { key: 'workingDirectory.staleWorktreeSnapshot', values: { name: worktreeName } }
+ : { key: 'workingDirectory.staleSnapshot' },
+ isWorktree,
+ pullRequest: git.github?.pullRequest ?? undefined,
+ ...(canReset
+ ? { reset: { name: getWorkingDirectoryName(sourcePath), targetPath: sourcePath! } }
+ : {}),
+ worktreePath,
+ };
+};
diff --git a/src/helpers/workingDirectoryPath.ts b/src/helpers/workingDirectoryPath.ts
index c12e104fa1a..85fd0a1041e 100644
--- a/src/helpers/workingDirectoryPath.ts
+++ b/src/helpers/workingDirectoryPath.ts
@@ -1,4 +1,4 @@
-import type { WorkingDirConfig, WorkingDirRepoType } from '@lobechat/types';
+import type { WorkingDirConfig, WorkingDirGitState, WorkingDirRepoType } from '@lobechat/types';
import { isDesktop } from '@/const/version';
@@ -35,3 +35,22 @@ export const getWorkingDirectoryName = (path?: string | null) => {
return value.replaceAll('\\', '/').split('/').findLast(Boolean) || value;
};
+
+/**
+ * Whether the effective checkout is a linked worktree rather than the source
+ * repo itself. `isWorktree` is only stamped by the newer snapshot writer, so
+ * topics recorded before it exist fall back to comparing the two paths.
+ *
+ * Shared by the topic meta hover card and the ControlBar's stale snapshot so a
+ * topic can't be a worktree on one surface and a plain checkout on the other.
+ */
+export const isWorktreeCheckout = ({
+ effectivePath,
+ git,
+ sourcePath,
+}: {
+ effectivePath?: string;
+ git?: WorkingDirGitState;
+ sourcePath?: string;
+}): boolean =>
+ !!git?.isWorktree || (!!sourcePath && !!effectivePath && effectivePath !== sourcePath);