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(git): refresh branch label when switching working directory (#16358)

Arvin Xu619c71216862
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index a527f6259ea..868623c920f 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -10,7 +10,8 @@ import { electronSystemService } from '@/services/electron/system';
import { gitService } from '@/services/git';
import {
useFetchGitAheadBehind,
- useFetchGitInfo,
+ useFetchGitBranch,
+ useFetchGitLinkedPR,
useFetchGitWorkingTreeStatus,
} from '@/store/device';
import { useGlobalStore } from '@/store/global';
@@ -155,7 +156,12 @@ const GitStatus = memo<GitStatusProps>(({ path, 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.
- const { data, mutate } = useFetchGitInfo(deviceId, path, isGithub);
+ // 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: workingStatus, mutate: mutateWorkingStatus } = useFetchGitWorkingTreeStatus(
deviceId,
path,
@@ -170,10 +176,10 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);
const handleOpenPr = useCallback(() => {
- if (data?.pullRequest?.url) {
- void electronSystemService.openExternalLink(data.pullRequest.url);
+ if (prData?.pullRequest?.url) {
+ void electronSystemService.openExternalLink(prData.pullRequest.url);
}
- }, [data?.pullRequest?.url]);
+ }, [prData?.pullRequest?.url]);
const handleToggleReview = useCallback(() => {
if (showRightPanel && workingSidebarTab === 'review') {
@@ -185,27 +191,18 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
}, [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel]);
const refreshAfterSync = useCallback(async () => {
- await Promise.all([mutate(), mutateWorkingStatus(), mutateAheadBehind()]);
- }, [mutate, mutateWorkingStatus, mutateAheadBehind]);
+ await Promise.all([mutateBranch(), mutatePR(), mutateWorkingStatus(), mutateAheadBehind()]);
+ }, [mutateBranch, mutatePR, mutateWorkingStatus, mutateAheadBehind]);
- // Flip the displayed branch instantly on checkout; clear the old branch's PR
- // (the new branch's is unknown until revalidate). No revalidate here β€” the
- // switcher's onAfterCheckout reconciles once the checkout lands.
+ // 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(
- (branch: string) => {
- void mutate(
- (prev) => ({
- ...prev,
- branch,
- detached: false,
- extraCount: undefined,
- ghMissing: undefined,
- pullRequest: null,
- }),
- { revalidate: false },
- );
+ (nextBranch: string) => {
+ void mutateBranch({ branch: nextBranch, detached: false }, { revalidate: false });
},
- [mutate],
+ [mutateBranch],
);
const syncBusy = pulling || pushing;
@@ -250,20 +247,18 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
}
}, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
- if (!data?.branch) return null;
+ if (!branch) return null;
- const branchTooltip = data.detached
- ? t('workingDirectory.detachedHead', { sha: data.branch })
- : data.branch;
+ const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;
- const prTooltip = data.pullRequest
- ? data.extraCount
+ const prTooltip = prData?.pullRequest
+ ? prData.extraCount
? t('workingDirectory.prTooltipWithExtra', {
- count: data.extraCount,
- title: data.pullRequest.title,
+ count: prData.extraCount,
+ title: prData.pullRequest.title,
})
- : data.pullRequest.title
- : data.ghMissing
+ : prData.pullRequest.title
+ : prData?.ghMissing
? t('workingDirectory.ghMissing')
: undefined;
@@ -286,17 +281,17 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
const branchTrigger = (
<div className={styles.trigger}>
<Icon icon={GitBranchIcon} size={12} />
- <span className={styles.branchLabel}>{data.branch}</span>
+ <span className={styles.branchLabel}>{branch}</span>
</div>
);
- const branchNode = data.detached ? (
+ 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
- currentBranch={data.branch}
+ currentBranch={branch}
deviceId={deviceId}
open={switcherOpen}
path={path}
@@ -304,7 +299,8 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
onOpenChange={setSwitcherOpen}
onOptimisticCheckout={handleOptimisticCheckout}
onAfterCheckout={() => {
- void mutate();
+ void mutateBranch();
+ void mutatePR();
void mutateWorkingStatus();
void mutateAheadBehind();
}}
@@ -388,13 +384,13 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
{pullNode}
{pushNode}
{diffNode}
- {data.pullRequest && (
+ {prData?.pullRequest && (
<>
<div className={styles.separator} />
<Tooltip title={prTooltip}>
<div className={styles.prTrigger} role="button" onClick={handleOpenPr}>
<Icon icon={GitPullRequest} size={12} />
- <span>#{data.pullRequest.number}</span>
+ <span>#{prData.pullRequest.number}</span>
</div>
</Tooltip>
</>
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index f78894980c1..7c0e4ac9430 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -15,10 +15,12 @@ const globalStoreMock = vi.hoisted(() => ({
const gitHookMocks = vi.hoisted(() => ({
mutateAheadBehind: vi.fn(),
- mutateGitInfo: vi.fn(),
+ mutateBranch: vi.fn(),
+ mutatePR: vi.fn(),
mutateWorkingTreeStatus: vi.fn(),
useFetchGitAheadBehind: vi.fn(),
- useFetchGitInfo: vi.fn(),
+ useFetchGitBranch: vi.fn(),
+ useFetchGitLinkedPR: vi.fn(),
useFetchGitWorkingTreeStatus: vi.fn(),
}));
@@ -28,7 +30,8 @@ vi.mock('../BranchSwitcher', () => ({
vi.mock('@/store/device', () => ({
useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,
- useFetchGitInfo: gitHookMocks.useFetchGitInfo,
+ useFetchGitBranch: gitHookMocks.useFetchGitBranch,
+ useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,
useFetchGitWorkingTreeStatus: gitHookMocks.useFetchGitWorkingTreeStatus,
}));
@@ -86,9 +89,13 @@ beforeEach(() => {
globalStoreMock.status.showRightPanel = false;
globalStoreMock.status.workingSidebarTab = 'resources';
- gitHookMocks.useFetchGitInfo.mockReturnValue({
- data: { branch: 'fix/remote-review', detached: false, pullRequest: null },
- mutate: gitHookMocks.mutateGitInfo,
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: { branch: 'fix/remote-review', detached: false },
+ mutate: gitHookMocks.mutateBranch,
+ });
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: { pullRequest: null },
+ mutate: gitHookMocks.mutatePR,
});
gitHookMocks.useFetchGitWorkingTreeStatus.mockReturnValue({
data: { added: 1, clean: false, deleted: 0, modified: 2, total: 3 },
diff --git a/src/features/Fleet/AgentColumn.tsx b/src/features/Fleet/AgentColumn.tsx
index 61102bff817..8fd0da1f6fd 100644
--- a/src/features/Fleet/AgentColumn.tsx
+++ b/src/features/Fleet/AgentColumn.tsx
@@ -34,7 +34,7 @@ import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath
import { useOperationState } from '@/hooks/useOperationState';
import { useChatStore } from '@/store/chat';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { useFetchGitInfo } from '@/store/device/gitHooks';
+import { useFetchGitBranch } from '@/store/device/gitHooks';
import { useElectronStore } from '@/store/electron';
import { type ChatTopicStatus } from '@/types/topic';
@@ -179,7 +179,7 @@ const buildChatPath = (column: FleetColumn) =>
/** Working directory + git branch subtitle (branch resolved live for local cwd). */
const WorkingDirRow = memo<{ workingDirectory: string }>(({ workingDirectory }) => {
- const { data } = useFetchGitInfo(undefined, workingDirectory);
+ const { data } = useFetchGitBranch(undefined, workingDirectory);
const dirName = workingDirectory.split('/').findLast(Boolean) ?? workingDirectory;
return (
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index c7564841976..752ff9645cb 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -412,11 +412,22 @@ export const deviceKeys = {
deviceId,
path,
]),
+ gitBranch: def('device:gitBranch', (deviceId: string, path: string) => [
+ 'device:gitBranch',
+ deviceId,
+ path,
+ ]),
gitBranches: def('device:gitBranches', (deviceId: string, path: string) => [
'device:gitBranches',
deviceId,
path,
]),
+ gitLinkedPR: def('device:gitLinkedPR', (deviceId: string, path: string, branch: string) => [
+ 'device:gitLinkedPR',
+ deviceId,
+ path,
+ branch,
+ ]),
gitRemoteBranches: def('device:gitRemoteBranches', (deviceId: string, dirPath: string) => [
'device:gitRemoteBranches',
deviceId,
@@ -432,12 +443,6 @@ export const deviceKeys = {
baseRef,
],
),
- gitInfo: def('device:gitInfo', (deviceId: string, path: string, isGithub: boolean) => [
- 'device:gitInfo',
- deviceId,
- path,
- isGithub,
- ]),
gitWorkingTreeStatus: def('device:gitWorkingTreeStatus', (deviceId: string, path: string) => [
'device:gitWorkingTreeStatus',
deviceId,
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
index ce0e07c13bd..5b0a7bcbcb6 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
@@ -23,7 +23,7 @@ import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
-import { useFetchGitInfo } from '@/store/device';
+import { useFetchGitBranch } from '@/store/device';
import FileRow from './FileRow';
import GroupHeader from './GroupHeader';
@@ -239,9 +239,9 @@ const Review = memo<ReviewProps>(({ deviceId, workingDirectory }) => {
const headRef = data?.mode === 'branch' ? data.headRef : undefined;
// Parent branch β€” only needed for the group header label, so we only fetch
// it when there's at least one submodule group to render alongside it.
- // SWR-deduped under the hood by `useFetchGitInfo`'s own cache key. Routes
+ // SWR-deduped under the hood by `useFetchGitBranch`'s own cache key. Routes
// through the target device so remote repos resolve the same way.
- const { data: parentGitInfo } = useFetchGitInfo(
+ const { data: parentGitInfo } = useFetchGitBranch(
deviceId,
submoduleGroups.length > 0 ? workingDirectory : undefined,
);
diff --git a/src/services/git.ts b/src/services/git.ts
index 4ac9ccb1b51..a3184e21cfe 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -20,10 +20,14 @@ import type {
import { lambdaClient } from '@/libs/trpc/client';
import { electronGitService } from '@/services/electron/git';
-/** Branch + linked-PR summary, composed from the branch and PR reads. */
-export interface GitInfo {
+/** Current branch + detached-HEAD state for a working directory (cheap read). */
+export interface GitBranchSummary {
branch?: string;
detached?: boolean;
+}
+
+/** Linked-PR summary for a branch β€” the result of the expensive `gh` leg. */
+export interface GitLinkedPRSummary {
extraCount?: number;
ghMissing?: boolean;
pullRequest?: DeviceGitLinkedPullRequest | null;
@@ -126,37 +130,43 @@ class GitService {
}
/**
- * Branch + linked PR summary. Composes a branch read with a conditional PR
- * lookup (skipped for detached HEAD / non-github repos) β€” both legs dispatch
- * per `deviceId`, so the gh-CLI lookup runs on whichever machine owns the repo.
+ * Current branch + detached-HEAD state. A cheap local git read, deliberately
+ * split from the linked-PR lookup so the branch label can revalidate promptly
+ * on a working-directory switch without re-triggering the expensive `gh` call.
+ * Dispatches per `deviceId` like every other leg.
*/
- async getGitInfo({
+ async getGitBranch({
deviceId,
- isGithub,
path,
}: {
deviceId?: string;
- isGithub?: boolean;
path: string;
- }): Promise<GitInfo> {
- const branchInfo = deviceId
+ }): Promise<GitBranchSummary> {
+ const info = deviceId
? await lambdaClient.device.gitBranch.query({ deviceId, path })
: await electronGitService.getGitBranch(path);
- const branch = branchInfo?.branch;
- const detached = branchInfo?.detached;
- if (!branch) return {};
-
- // Skip the PR lookup for detached HEAD or non-github repos.
- if (detached || !isGithub) return { branch, detached };
+ return { branch: info?.branch, detached: info?.detached };
+ }
+ /**
+ * PR linked to `branch` on a GitHub repo. Shells out to `gh pr list` (8s
+ * timeout), so callers throttle this far more aggressively than the branch
+ * read. Returns `undefined` when nothing is linked / the lookup is skipped.
+ */
+ async getLinkedPullRequest({
+ branch,
+ deviceId,
+ path,
+ }: {
+ branch: string;
+ deviceId?: string;
+ path: string;
+ }): Promise<GitLinkedPRSummary | undefined> {
const pr = deviceId
? await lambdaClient.device.gitLinkedPullRequest.query({ branch, deviceId, path })
: await electronGitService.getLinkedPullRequest({ branch, path });
- if (!pr) return { branch, detached };
-
+ if (!pr) return undefined;
return {
- branch,
- detached,
extraCount: pr.extraCount,
ghMissing: pr.status === 'gh-missing',
pullRequest: pr.pullRequest,
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 40835abd153..608156bd935 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -7,7 +7,7 @@ import type {
import { useClientDataSWR } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
-import { type GitInfo, gitService } from '@/services/git';
+import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/services/git';
/**
* Git read hooks for a working directory, transport-agnostic: the fetcher goes
@@ -20,13 +20,38 @@ const isEnabled = (deviceId: string | undefined, path: string | undefined): path
!!path && (!!deviceId || isDesktop);
/**
- * Branch + linked PR. PR lookup spawns `gh`, so dedupe + throttle focus
- * revalidation to 60s to avoid spamming the CLI.
+ * Current branch + detached state. A cheap local git read, so use a short
+ * dedupe window (2s): switching the working directory must refetch the branch
+ * promptly. A longer window would swallow SWR's key-change revalidation and
+ * leave the branch label stuck on the previous directory (only a manual
+ * `mutate()` refresh would recover it). 2s still collapses truly concurrent
+ * reads of the same dir.
*/
-export const useFetchGitInfo = (deviceId: string | undefined, path?: string, isGithub = false) =>
- useClientDataSWR<GitInfo>(
- isEnabled(deviceId, path) ? deviceKeys.gitInfo(deviceId ?? 'local', path, isGithub) : null,
- () => gitService.getGitInfo({ deviceId, isGithub, path: path! }),
+export const useFetchGitBranch = (deviceId: string | undefined, path?: string) =>
+ useClientDataSWR<GitBranchSummary>(
+ isEnabled(deviceId, path) ? deviceKeys.gitBranch(deviceId ?? 'local', path) : null,
+ () => gitService.getGitBranch({ deviceId, path: path! }),
+ { dedupingInterval: 2 * 1000, shouldRetryOnError: false },
+ );
+
+/**
+ * PR linked to the current branch. The lookup spawns `gh pr list` (8s timeout),
+ * so keep a long 60s dedupe + 60s focus throttle β€” unlike the cheap branch read,
+ * this must NOT re-run on every remount or directory revisit. Keyed by branch,
+ * so a checkout naturally re-keys into a fresh lookup; disabled for non-github
+ * repos and detached HEAD (no branch ref to query).
+ */
+export const useFetchGitLinkedPR = (
+ deviceId: string | undefined,
+ path: string | undefined,
+ branch: string | undefined,
+ isGithub = false,
+) =>
+ useClientDataSWR<GitLinkedPRSummary | undefined>(
+ isGithub && branch && isEnabled(deviceId, path)
+ ? deviceKeys.gitLinkedPR(deviceId ?? 'local', path, branch)
+ : null,
+ () => gitService.getLinkedPullRequest({ branch: branch!, deviceId, path: path! }),
{ dedupingInterval: 60 * 1000, focusThrottleInterval: 60 * 1000, shouldRetryOnError: false },
);