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.

⚡️ perf(git-status): paint Overview and chat-input git chips stale-first from replicas (#20841)

Arvin Xu78c316fe3e7a
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index b247af73730..0af01c39f0e 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -6,6 +6,7 @@
"workingDirectory.agentDescription": "Default working directory for all conversations with this Agent",
"workingDirectory.agentLevel": "Agent Working Directory",
"workingDirectory.bareWorktree": "bare",
+ "workingDirectory.branchConfirming": "Confirming the current branch…",
"workingDirectory.branchInWorktree": "In worktree {{name}}",
"workingDirectory.branchSearchPlaceholder": "Search branches",
"workingDirectory.branchesEmpty": "No local branches",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index edbb79df247..e7ce6838b47 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -6,6 +6,7 @@
"workingDirectory.agentDescription": "该助手下所有对话的默认工作目录",
"workingDirectory.agentLevel": "代理工作目录",
"workingDirectory.bareWorktree": "bare",
+ "workingDirectory.branchConfirming": "正在确认当前分支…",
"workingDirectory.branchInWorktree": "位于工作树 {{name}}",
"workingDirectory.branchSearchPlaceholder": "搜索分支",
"workingDirectory.branchesEmpty": "暂无本地分支",
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 08b0657010f..46037cd74dc 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -33,6 +33,7 @@ export default {
'workingDirectory.agentDescription':
'Default working directory for all conversations with this Agent',
'workingDirectory.agentLevel': 'Agent Working Directory',
+ 'workingDirectory.branchConfirming': 'Confirming the current branch…',
'workingDirectory.branchInWorktree': 'In worktree {{name}}',
'workingDirectory.branchSearchPlaceholder': 'Search branches',
'workingDirectory.branchesEmpty': 'No local branches',
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 889e5b83db7..c2f8999c1e7 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -1,7 +1,7 @@
import type { WorkingDirGitState } from '@lobechat/types';
import { createStaticStyles, cssVar, Icon, toast, Tooltip } from '@lobehub/ui';
import { ArrowDownIcon, ArrowUpIcon, GitPullRequest } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RingLoadingIcon from '@/components/RingLoading';
@@ -11,6 +11,7 @@ import {
useDeviceStore,
useFetchGitAheadBehind,
useFetchGitBranch,
+ useFetchGitDiffStats,
useFetchGitLinkedPR,
useFetchGitWorktrees,
useReviewPatches,
@@ -110,9 +111,11 @@ interface GitStatusProps {
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 /
+ * Git context persisted on the topic. Stands in for the live probe in two
+ * cases: while the probe is still pending (no cached branch yet), it paints a
+ * read-only branch / PR chip so the cluster doesn't pop in once the read lands;
+ * and when the probe finds no branch at `path` — which happens whenever the
+ * recorded worktree directory has since been deleted — it 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.
@@ -135,15 +138,19 @@ const GitStatus = memo<GitStatusProps>(
const {
data: branchData,
error: branchError,
+ isConfirmed: branchConfirmed,
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
+ // The persisted snapshot only stands in once the current probe has actually
+ // ANSWERED. A hydrated row (`data !== undefined`) is a paint-only stand-in,
+ // not an answer: treating it as settled would classify a dead directory
+ // from the last session before this session's read returns.
+ // `getGitBranch` resolves to `{}` for a path it can't read, so a settled
+ // probe is a confirmed read (or an errored one) — keying off `!branch` alone
// would flash the snapshot cluster on every mount while loading.
- const probeSettled = branchData !== undefined || !!branchError;
+ const probeSettled = branchConfirmed || !!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 —
@@ -154,7 +161,10 @@ const GitStatus = memo<GitStatusProps>(
(s) => !!deviceSelectors.getDeviceById(deviceId)(s)?.online,
);
const probeReachedDirectory = !deviceId || deviceOnline;
- const probeFoundNothing = !branch && probeSettled && probeReachedDirectory;
+ // Only a CONFIRMED empty probe may declare the directory gone. A hydrated
+ // empty row (`{}`) means the last session couldn't read it, not that it is
+ // gone now.
+ const probeFoundNothing = !branch && branchConfirmed && probeReachedDirectory;
// Worktrees picked from the bar were persisted without a branch, so the
// recorded worktree is all such a snapshot has. An empty probe alone can't
// condemn it: a remote read that fails in transit on a device still marked
@@ -165,11 +175,14 @@ const GitStatus = memo<GitStatusProps>(
!fallbackGit?.branch && sourcePath && sourcePath !== path
? fallbackGit?.activeWorktree
: undefined;
- const { data: sourceWorktrees } = useFetchGitWorktrees(
+ const { data: sourceWorktrees, isConfirmed: sourceWorktreesConfirmed } = useFetchGitWorktrees(
deviceId,
probeFoundNothing && recordedWorktree ? sourcePath : undefined,
);
+ // Only this session's answer may condemn the recorded worktree; a hydrated
+ // listing from the previous session is a paint-only stand-in.
const recordedWorktreeGone =
+ sourceWorktreesConfirmed &&
!!sourceWorktrees?.length &&
!sourceWorktrees.some((worktree) => worktree.path === path && !worktree.prunable);
const isStale =
@@ -191,15 +204,21 @@ const GitStatus = memo<GitStatusProps>(
deviceId,
!isStale,
);
+ // The `+N −M` chip is derived from the review patches (a separate read), so
+ // persist only its compact counts. That lets a reload paint the previous
+ // session's chip instead of growing the cluster after the diff arrives.
+ const { data: cachedDiffStats, set: setDiffStats } = useFetchGitDiffStats(deviceId, path);
const livePath = isStale ? undefined : path;
- const { data: aheadBehind, mutate: mutateAheadBehind } = useFetchGitAheadBehind(
- deviceId,
- livePath,
- );
- const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(
- deviceId,
- livePath,
- );
+ const {
+ data: aheadBehind,
+ isConfirmed: aheadBehindConfirmed,
+ mutate: mutateAheadBehind,
+ } = useFetchGitAheadBehind(deviceId, livePath);
+ const {
+ data: worktrees = [],
+ isConfirmed: worktreesConfirmed,
+ mutate: mutateWorktrees,
+ } = useFetchGitWorktrees(deviceId, livePath);
const [switcherOpen, setSwitcherOpen] = useState(false);
const [pulling, setPulling] = useState(false);
const [pushing, setPushing] = useState(false);
@@ -208,11 +227,22 @@ const GitStatus = memo<GitStatusProps>(
const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);
const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);
+ // Until the linked-PR lookup answers for this branch, reuse the PR the topic
+ // recorded for the same branch so the PR chip doesn't pop in late.
+ const pullRequest =
+ prData !== undefined
+ ? prData.pullRequest
+ : isGithub &&
+ (!branch || branch === fallbackGit?.branch) &&
+ fallbackGit?.github?.pullRequest
+ ? fallbackGit.github.pullRequest
+ : undefined;
+
const handleOpenPr = useCallback(() => {
- if (prData?.pullRequest?.url) {
- openTrustedExternalUrl(prData.pullRequest.url);
+ if (pullRequest?.url) {
+ openTrustedExternalUrl(pullRequest.url);
}
- }, [prData?.pullRequest?.url]);
+ }, [pullRequest?.url]);
const handleToggleReview = useCallback(() => {
if (showRightPanel && workingSidebarTab === 'review') {
@@ -244,6 +274,18 @@ const GitStatus = memo<GitStatusProps>(
);
const syncBusy = pulling || pushing;
+ // Stale-first paints the last branch and its counts immediately, but
+ // checkout / pull / push assume both still describe the live branch. When
+ // the repo was switched externally, the faster branch probe can confirm the
+ // NEW branch while the ahead/behind snapshot still belongs to the OLD one —
+ // acting then would pull/push the actual branch while the label and counts
+ // describe another. Keep them inert until BOTH reads answer; the chips stay
+ // visible either way.
+ const actionsBlocked = syncBusy || !branchConfirmed || !aheadBehindConfirmed;
+ // Both pickers consume the worktree list (the branch picker routes to the
+ // worktree that already holds the branch), so it must be this session's
+ // listing too — a stale one can point at a removed worktree.
+ const pickersReady = branchConfirmed && worktreesConfirmed;
const handlePull = useCallback(async () => {
if (pulling || pushing) return;
@@ -285,7 +327,7 @@ const GitStatus = memo<GitStatusProps>(
}
}, [deviceId, path, pulling, pushing, refreshAfterSync, t]);
- const diffStats = useMemo(() => {
+ const liveDiffStats = useMemo(() => {
const patches = [
...(reviewPatches?.patches ?? []),
...(reviewPatches?.submodules ?? []).flatMap((submodule) => submodule.patches),
@@ -300,6 +342,13 @@ const GitStatus = memo<GitStatusProps>(
{ additions: 0, deletions: 0, files: 0 },
);
}, [reviewPatches?.patches, reviewPatches?.submodules]);
+ // Persist the confirmed counts; an empty answer (no patches) also replaces
+ // the stale chip.
+ useEffect(() => {
+ if (reviewPatches !== undefined) setDiffStats(liveDiffStats);
+ }, [reviewPatches, liveDiffStats, setDiffStats]);
+ const diffStats =
+ reviewPatches !== undefined ? liveDiffStats : (cachedDiffStats ?? liveDiffStats);
const hasChanges = diffStats.files > 0;
// Dead directory: the whole live cluster is unreachable, so hand off to the
@@ -318,17 +367,44 @@ const GitStatus = memo<GitStatusProps>(
);
}
- if (!branch) return null;
+ if (!branch) {
+ // Probe still pending: paint the topic's recorded branch / PR read-only
+ // (not the dead-directory snapshot — nothing is known to be gone yet).
+ if (!probeSettled && fallbackGit?.branch) {
+ return (
+ <>
+ <div className={gitChipStyles.separator} />
+ <div aria-busy className={styles.branchGroup}>
+ <div className={gitChipStyles.trigger}>
+ <span className={styles.branchLabel}>{fallbackGit.branch}</span>
+ </div>
+ </div>
+ {pullRequest && (
+ <>
+ <div className={gitChipStyles.separator} />
+ <Tooltip title={pullRequest.title}>
+ <div className={gitChipStyles.prTrigger} role="button" onClick={handleOpenPr}>
+ <Icon icon={GitPullRequest} size={12} />
+ <span>#{pullRequest.number}</span>
+ </div>
+ </Tooltip>
+ </>
+ )}
+ </>
+ );
+ }
+ return null;
+ }
const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;
- const prTooltip = prData?.pullRequest
- ? prData.extraCount
+ const prTooltip = pullRequest
+ ? prData?.extraCount
? t('workingDirectory.prTooltipWithExtra', {
count: prData.extraCount,
- title: prData.pullRequest.title,
+ title: pullRequest.title,
})
- : prData.pullRequest.title
+ : pullRequest.title
: prData?.ghMissing
? t('workingDirectory.ghMissing')
: undefined;
@@ -361,6 +437,7 @@ const GitStatus = memo<GitStatusProps>(
currentBranch={branch}
detached={detached}
deviceId={deviceId}
+ disabled={!pickersReady}
isGithub={isGithub}
path={path}
sourcePath={sourcePath ?? path}
@@ -373,6 +450,11 @@ const GitStatus = memo<GitStatusProps>(
const branchNode = detached ? (
// Detached HEAD → plain branch label (nothing to switch to).
<Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
+ ) : !pickersReady ? (
+ // Hydrated from the last session: hold the checkout entry until this
+ // session's branch AND worktree probes answer, so the switcher's "current"
+ // branch and its worktree routing are not stale guesses.
+ <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>
) : (
// Local switches over IPC; a remote device switches over RPC (deviceId set).
<BranchSwitcher
@@ -418,10 +500,10 @@ const GitStatus = memo<GitStatusProps>(
<Tooltip title={pullTooltip}>
<div
aria-busy={pulling}
- aria-disabled={syncBusy}
- className={`${styles.syncTrigger} ${styles.behindStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ aria-disabled={actionsBlocked}
+ className={`${styles.syncTrigger} ${styles.behindStat} ${actionsBlocked ? styles.syncTriggerDisabled : ''}`}
role="button"
- onClick={syncBusy ? undefined : handlePull}
+ onClick={actionsBlocked ? undefined : handlePull}
>
<span className={styles.aheadBehindStat}>
{pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}
@@ -435,10 +517,10 @@ const GitStatus = memo<GitStatusProps>(
<Tooltip title={pushTooltip}>
<div
aria-busy={pushing}
- aria-disabled={syncBusy}
- className={`${styles.syncTrigger} ${styles.aheadStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ aria-disabled={actionsBlocked}
+ className={`${styles.syncTrigger} ${styles.aheadStat} ${actionsBlocked ? styles.syncTriggerDisabled : ''}`}
role="button"
- onClick={syncBusy ? undefined : handlePush}
+ onClick={actionsBlocked ? undefined : handlePush}
>
<span className={styles.aheadBehindStat}>
{pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}
@@ -480,13 +562,13 @@ const GitStatus = memo<GitStatusProps>(
{pullNode}
{pushNode}
{diffNode}
- {prData?.pullRequest && (
+ {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>
+ <span>#{pullRequest.number}</span>
</div>
</Tooltip>
</>
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index f5cc046e2fe..54ffda741f7 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -418,6 +418,8 @@ interface WorktreeSwitcherProps {
currentBranch: string;
detached?: boolean;
deviceId?: string;
+ /** Mounted but inert while a stale-first branch awaits confirmation. */
+ disabled?: boolean;
isGithub: boolean;
onWorktreesChange?: () => Promise<unknown> | unknown;
path: string;
@@ -436,6 +438,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
currentBranch,
detached,
deviceId,
+ disabled = false,
isGithub,
onWorktreesChange,
path,
@@ -638,9 +641,18 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
);
return (
- <DropdownMenuRoot open={open} onOpenChange={setOpen}>
+ <DropdownMenuRoot
+ open={!disabled && open}
+ onOpenChange={(next) => {
+ if (!disabled) setOpen(next);
+ }}
+ >
<DropdownMenuTrigger>
- <div className={gitMenuTriggerStyles.trigger}>
+ <div
+ aria-disabled={disabled}
+ className={gitMenuTriggerStyles.trigger}
+ data-disabled={disabled || undefined}
+ >
{open ? trigger : <Tooltip title={triggerTitle}>{trigger}</Tooltip>}
</div>
</DropdownMenuTrigger>
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 611cfb2558c..299ce110cc7 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -2,6 +2,8 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { gitService } from '@/services/git';
+
import GitStatus from '../GitStatus';
const globalStoreMock = vi.hoisted(() => ({
@@ -23,8 +25,10 @@ const gitHookMocks = vi.hoisted(() => ({
mutatePR: vi.fn(),
mutateReviewPatches: vi.fn(),
mutateWorktrees: vi.fn(),
+ setDiffStats: vi.fn(),
useFetchGitAheadBehind: vi.fn(),
useFetchGitBranch: vi.fn(),
+ useFetchGitDiffStats: vi.fn(),
useFetchGitLinkedPR: vi.fn(),
useReviewPatches: vi.fn(),
useFetchGitWorktrees: vi.fn(),
@@ -35,7 +39,9 @@ vi.mock('../BranchSwitcher', () => ({
}));
vi.mock('../WorktreeSwitcher', () => ({
- default: () => <span data-testid="worktree-switcher" />,
+ default: ({ disabled }: { disabled?: boolean }) => (
+ <span data-disabled={Boolean(disabled)} data-testid="worktree-switcher" />
+ ),
}));
vi.mock('../StaleGitSnapshot', () => ({
@@ -53,6 +59,7 @@ vi.mock('@/store/device', () => ({
selector(deviceStoreMock),
useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,
useFetchGitBranch: gitHookMocks.useFetchGitBranch,
+ useFetchGitDiffStats: gitHookMocks.useFetchGitDiffStats,
useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,
useReviewPatches: gitHookMocks.useReviewPatches,
useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,
@@ -99,6 +106,7 @@ beforeEach(() => {
gitHookMocks.useFetchGitBranch.mockReturnValue({
data: { branch: 'fix/remote-review', detached: false },
+ isConfirmed: true,
mutate: gitHookMocks.mutateBranch,
});
gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
@@ -128,12 +136,17 @@ beforeEach(() => {
});
gitHookMocks.useFetchGitWorktrees.mockReturnValue({
data: [],
+ isConfirmed: true,
mutate: gitHookMocks.mutateWorktrees,
});
+ gitHookMocks.useFetchGitDiffStats.mockReturnValue({
+ data: undefined,
+ set: gitHookMocks.setDiffStats,
+ });
});
describe('GitStatus', () => {
- it('opens the review panel when clicking remote device diff stats', () => {
+ it('opens the review panel when clicking remote device diff stats', async () => {
render(<GitStatus agentId="agent-1" deviceId="device-1" isGithub={false} path="/repo" />);
expect(gitHookMocks.useReviewPatches).toHaveBeenCalledWith(
@@ -145,6 +158,14 @@ describe('GitStatus', () => {
);
expect(screen.getByText('+3')).toBeInTheDocument();
expect(screen.getByText('-1')).toBeInTheDocument();
+ // The confirmed counts are handed to the replica so a reload can paint them.
+ await waitFor(() =>
+ expect(gitHookMocks.setDiffStats).toHaveBeenCalledWith({
+ additions: 3,
+ deletions: 1,
+ files: 1,
+ }),
+ );
fireEvent.click(screen.getByRole('button'));
@@ -177,6 +198,128 @@ describe('GitStatus', () => {
});
});
+ // The diff counts come from a separate read. Their persisted copy keeps the
+ // composer cluster stable while that read is still in flight.
+ it('paints the persisted change counts while the review patches load', () => {
+ gitHookMocks.useReviewPatches.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutateReviewPatches,
+ });
+ gitHookMocks.useFetchGitDiffStats.mockReturnValue({
+ data: { additions: 4, deletions: 2, files: 2 },
+ set: gitHookMocks.setDiffStats,
+ });
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" />);
+
+ expect(screen.getByText('+4')).toBeInTheDocument();
+ expect(screen.getByText('-2')).toBeInTheDocument();
+ expect(gitHookMocks.setDiffStats).not.toHaveBeenCalled();
+ });
+
+ // Review P1: the stale-first branch is a paint-only stand-in. Checkout, pull
+ // and push must wait until this session's probe confirms it.
+ it('keeps checkout, pull and push inert until the current probe confirms the branch', () => {
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: { branch: 'fix/remote-review', detached: false },
+ isConfirmed: false,
+ mutate: gitHookMocks.mutateBranch,
+ });
+ gitHookMocks.useFetchGitAheadBehind.mockReturnValue({
+ data: { ahead: 2, behind: 1, hasUpstream: true, upstream: 'origin/fix/remote-review' },
+ mutate: gitHookMocks.mutateAheadBehind,
+ });
+ gitHookMocks.useFetchGitWorktrees.mockReturnValue({
+ data: [
+ { branch: 'fix/remote-review', current: true, path: '/repo' },
+ { branch: 'canary', current: false, path: '/repo-canary' },
+ ],
+ mutate: gitHookMocks.mutateWorktrees,
+ });
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);
+
+ // The branch label still paints…
+ expect(screen.getByText('fix/remote-review')).toBeInTheDocument();
+ // …and the worktree entry stays mounted (removing it would shift the branch
+ // chip when it returns) but is inert until confirmation.
+ expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'true');
+ const push = screen.getByText('2').closest('[role="button"]')!;
+ const pull = screen.getByText('1').closest('[role="button"]')!;
+ expect(push).toHaveAttribute('aria-disabled', 'true');
+ expect(pull).toHaveAttribute('aria-disabled', 'true');
+
+ fireEvent.click(push);
+ fireEvent.click(pull);
+ expect(gitService.pushGitBranch).not.toHaveBeenCalled();
+ expect(gitService.pullGitBranch).not.toHaveBeenCalled();
+ });
+
+ // Review P1: after a reload where the repository was switched externally from
+ // A to B, the faster branch probe confirms B while the persisted ahead/behind
+ // row still describes A. Enabling sync there would pull/push the ACTUAL branch
+ // B using A's counts and target text, so that read must confirm too.
+ it('keeps pull and push inert while ahead/behind is still the previous snapshot', async () => {
+ gitHookMocks.useFetchGitAheadBehind.mockReturnValue({
+ data: { ahead: 2, behind: 1, hasUpstream: true, upstream: 'origin/previous' },
+ isConfirmed: false,
+ mutate: gitHookMocks.mutateAheadBehind,
+ });
+
+ const { unmount } = render(
+ <GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />,
+ );
+
+ // The previous snapshot keeps painting (that is the point of stale-first)…
+ const push = screen.getByText('2').closest('[role="button"]')!;
+ const pull = screen.getByText('1').closest('[role="button"]')!;
+ expect(push).toHaveAttribute('aria-disabled', 'true');
+ expect(pull).toHaveAttribute('aria-disabled', 'true');
+
+ // …but neither action may run against it.
+ fireEvent.click(push);
+ fireEvent.click(pull);
+ expect(gitService.pushGitBranch).not.toHaveBeenCalled();
+ expect(gitService.pullGitBranch).not.toHaveBeenCalled();
+
+ // Once the live ahead/behind read answers, the same chips become actionable.
+ gitHookMocks.useFetchGitAheadBehind.mockReturnValue({
+ data: { ahead: 2, behind: 1, hasUpstream: true, upstream: 'origin/current' },
+ isConfirmed: true,
+ mutate: gitHookMocks.mutateAheadBehind,
+ });
+ // `GitStatus` is memoized, so a same-prop rerender bails out; remount instead.
+ unmount();
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);
+
+ const readyPush = screen.getByText('2').closest('[role="button"]')!;
+ expect(readyPush).toHaveAttribute('aria-disabled', 'false');
+ });
+
+ // Review P1: the branch picker routes through the worktree list. A confirmed
+ // branch alone must not enable a picker that still holds last session's
+ // worktrees — it could point at a worktree removed externally.
+ it('keeps both pickers inert until the worktree list itself is confirmed', () => {
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: { branch: 'fix/remote-review', detached: false },
+ isConfirmed: true,
+ mutate: gitHookMocks.mutateBranch,
+ });
+ gitHookMocks.useFetchGitWorktrees.mockReturnValue({
+ data: [
+ { branch: 'fix/remote-review', current: true, path: '/repo' },
+ { branch: 'canary', current: false, path: '/repo-canary' },
+ ],
+ isConfirmed: false,
+ mutate: gitHookMocks.mutateWorktrees,
+ });
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);
+
+ // The trigger keeps its width (no layout jump) but cannot switch.
+ expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'true');
+ });
+
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
@@ -193,6 +336,7 @@ describe('GitStatus', () => {
// probe that found no branch, not a pending one.
gitHookMocks.useFetchGitBranch.mockReturnValue({
data: {},
+ isConfirmed: true,
mutate: gitHookMocks.mutateBranch,
});
});
@@ -226,6 +370,7 @@ describe('GitStatus', () => {
gitHookMocks.useFetchGitWorktrees.mockImplementation(
(_deviceId: string | undefined, path?: string) => ({
data: path === '/repo' ? listing : [],
+ isConfirmed: true,
mutate: gitHookMocks.mutateWorktrees,
}),
);
@@ -302,13 +447,13 @@ describe('GitStatus', () => {
);
});
- it('stays empty while the probe is still pending, so no stale flash', () => {
+ it('does not flash the dead-directory snapshot while the probe is still pending', () => {
gitHookMocks.useFetchGitBranch.mockReturnValue({
data: undefined,
mutate: gitHookMocks.mutateBranch,
});
- const { container } = render(
+ render(
<GitStatus
isGithub
agentId="agent-1"
@@ -317,7 +462,7 @@ describe('GitStatus', () => {
/>,
);
- expect(container).toBeEmptyDOMElement();
+ expect(screen.queryByTestId('stale-git-snapshot')).not.toBeInTheDocument();
});
it('renders nothing when the topic carries no git snapshot either', () => {
@@ -393,18 +538,107 @@ describe('GitStatus', () => {
});
});
+ describe('probe still pending (cold load, nothing cached yet)', () => {
+ const fallbackGit = {
+ branch: 'feat/stale-first',
+ github: {
+ pullRequest: {
+ number: 42,
+ state: 'OPEN',
+ title: 'Stale-first git chips',
+ url: 'https://github.com/lobehub/lobehub/pull/42',
+ },
+ },
+ };
+
+ beforeEach(() => {
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutateBranch,
+ });
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutatePR,
+ });
+ });
+
+ // Regression: the bar rendered nothing until the branch probe answered, so
+ // the whole branch / PR cluster popped in after every reload even though the
+ // topic already carried a persisted git snapshot.
+ it('paints the persisted branch and PR snapshot instead of collapsing', () => {
+ render(<GitStatus isGithub agentId="agent-1" fallbackGit={fallbackGit} path="/repo" />);
+
+ expect(screen.getByText('feat/stale-first')).toBeInTheDocument();
+ expect(screen.getByText('#42')).toBeInTheDocument();
+ expect(screen.queryByTestId('stale-git-snapshot')).not.toBeInTheDocument();
+ });
+
+ it('stays empty when the topic carries no snapshot', () => {
+ const { container } = render(<GitStatus isGithub agentId="agent-1" path="/repo" />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+ });
+
+ it('keeps the recorded PR chip while the linked-PR lookup for the same branch loads', () => {
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutatePR,
+ });
+
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ path="/repo"
+ fallbackGit={{
+ branch: 'fix/remote-review',
+ github: {
+ pullRequest: { number: 7, state: 'OPEN', title: 'Remote review', url: 'https://x/7' },
+ },
+ }}
+ />,
+ );
+
+ expect(screen.getByText('#7')).toBeInTheDocument();
+ });
+
+ it('drops the recorded PR chip once the live branch differs from the snapshot', () => {
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: undefined,
+ mutate: gitHookMocks.mutatePR,
+ });
+
+ render(
+ <GitStatus
+ isGithub
+ agentId="agent-1"
+ path="/repo"
+ fallbackGit={{
+ branch: 'other-branch',
+ github: {
+ pullRequest: { number: 7, state: 'OPEN', title: 'Other', url: 'https://x/7' },
+ },
+ }}
+ />,
+ );
+
+ expect(screen.queryByText('#7')).not.toBeInTheDocument();
+ });
+
it('keeps branch switching visible when worktrees are available', () => {
gitHookMocks.useFetchGitWorktrees.mockReturnValue({
data: [
{ branch: 'fix/remote-review', current: true, path: '/repo' },
{ branch: 'canary', current: false, path: '/repo-canary' },
],
+ isConfirmed: true,
mutate: gitHookMocks.mutateWorktrees,
});
render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);
- expect(screen.getByTestId('worktree-switcher')).toBeInTheDocument();
+ expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'false');
expect(screen.getByText('fix/remote-review')).toBeInTheDocument();
});
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
index 21ad826f706..2272924c33d 100644
--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
@@ -130,6 +130,32 @@ describe('WorktreeSwitcher', () => {
expect(within(trigger).getByTestId('worktree-tooltip')).toBeTruthy();
});
+ it('keeps the trigger mounted but inert while the branch is unconfirmed', () => {
+ render(
+ <WorktreeSwitcher
+ disabled
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ const trigger = screen.getByTestId('worktree-dropdown-trigger');
+ // Same DOM and icon as the enabled trigger — only the action is gated.
+ expect(within(trigger).getByTestId('icon')).toBeTruthy();
+ expect(trigger.firstElementChild).toHaveAttribute('aria-disabled', 'true');
+ });
+
it('shows a branch icon on the main worktree and a fork icon on a linked one', () => {
const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
const worktrees = [
diff --git a/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts b/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts
index 98a7a848790..ec1897dc49e 100644
--- a/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts
+++ b/src/features/ChatInput/ControlBar/gitMenuTriggerStyles.ts
@@ -22,5 +22,12 @@ export const gitMenuTriggerStyles = createStaticStyles(({ css }) => ({
&[data-popup-open] > * {
background: ${cssVar.colorFillTertiary};
}
+
+ /* Stale-first: the trigger stays in place (no layout jump) but cannot
+ checkout until the current probe confirms the branch. */
+ &[aria-disabled='true'] > * {
+ cursor: not-allowed;
+ opacity: 0.6;
+ }
`,
}));
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
index 759b72753bc..e0c7da3e4d8 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
@@ -5,6 +5,7 @@ import {
getStatusDeviceId,
isLinkedWorktreeCheckout,
shouldShowCiLabel,
+ shouldShowGitSkeleton,
} from '../overviewData';
describe('collectChangeStats', () => {
@@ -91,3 +92,20 @@ describe('getStatusDeviceId', () => {
expect(getStatusDeviceId('device', undefined)).toBeUndefined();
});
});
+
+describe('shouldShowGitSkeleton', () => {
+ it('shows the skeleton only on a first-ever load with no git data at all', () => {
+ expect(shouldShowGitSkeleton({ hasData: false, loading: true })).toBe(true);
+ });
+
+ // Regression: the skeleton keyed off `branchLoading || reviewLoading`, so a
+ // reload with a cached branch still blanked the whole section until the diff
+ // patches came back.
+ it('keeps rendering cached rows while other git reads are still in flight', () => {
+ expect(shouldShowGitSkeleton({ hasData: true, loading: true })).toBe(false);
+ });
+
+ it('never shows the skeleton once loading settles', () => {
+ expect(shouldShowGitSkeleton({ hasData: false, loading: false })).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index 5695487c27b..9fe51d2481c 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -59,7 +59,12 @@ import { labPreferSelectors } from '@/store/user/selectors';
import GoalSection from '../GoalSection';
import ProgressSection from '../ProgressSection';
import DeviceStatusSection from './DeviceStatusSection';
-import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';
+import {
+ collectChangeStats,
+ isLinkedWorktreeCheckout,
+ shouldShowCiLabel,
+ shouldShowGitSkeleton,
+} from './overviewData';
import OverviewHeader from './OverviewHeader';
import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';
import PortSwitcher from './PortSwitcher';
@@ -124,6 +129,7 @@ const Overview = memo<OverviewProps>(
const {
data: branchData,
error: branchError,
+ isConfirmed: branchConfirmed,
isLoading: branchLoading,
mutate: mutateBranch,
} = useFetchGitBranch(deviceId, gitPath);
@@ -132,6 +138,7 @@ const Overview = memo<OverviewProps>(
const {
data: aheadBehind,
error: aheadBehindError,
+ isConfirmed: aheadBehindConfirmed,
mutate: mutateAheadBehind,
} = useFetchGitAheadBehind(deviceId, gitPath);
const {
@@ -140,10 +147,13 @@ const Overview = memo<OverviewProps>(
isLoading: reviewLoading,
mutate: mutateReview,
} = useReviewPatches(gitPath, 'unstaged', undefined, deviceId, active);
- const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(
- deviceId,
- gitPath,
- );
+ const {
+ data: worktreesData,
+ isConfirmed: worktreesConfirmed,
+ isLoading: worktreesLoading,
+ mutate: mutateWorktrees,
+ } = useFetchGitWorktrees(deviceId, gitPath);
+ const worktrees = worktreesData ?? [];
const [switcherOpen, setSwitcherOpen] = useState(false);
const [pulling, setPulling] = useState(false);
const [pushing, setPushing] = useState(false);
@@ -151,7 +161,20 @@ const Overview = memo<OverviewProps>(
const changeStats = useMemo(() => collectChangeStats(reviewData), [reviewData]);
const gitError = branchError || aheadBehindError || reviewError;
- const isGitLoading = branchLoading || reviewLoading;
+ // Stale-first: the small git reads are replicas (`@/store/device/gitStatus`),
+ // so after a reload they paint from the persisted copy while the rest (e.g.
+ // the diff patches) are still in flight. Only fall back to the skeleton when
+ // nothing at all is there yet; rows whose own read is pending render a
+ // placeholder instead.
+ const isGitLoading = shouldShowGitSkeleton({
+ hasData:
+ branchData !== undefined ||
+ aheadBehind !== undefined ||
+ reviewData !== undefined ||
+ worktreesData !== undefined,
+ loading: branchLoading || reviewLoading || worktreesLoading,
+ });
+ const changesPending = reviewData === undefined && reviewLoading;
const visibleWorks = works.slice(0, 3);
const directoryName = workingDirectory ? pathBasename(workingDirectory) : undefined;
const hasWorkspace = environmentAvailable && !!workingDirectory;
@@ -178,6 +201,12 @@ const Overview = memo<OverviewProps>(
);
const syncBusy = pulling || pushing;
+ // The branch and its counts may be stale-first paints from the last
+ // session. Checkout, pull and push assume both still describe the live
+ // branch, so they stay inert until this session confirms both reads — a
+ // faster branch probe must not enable sync against the previous branch's
+ // ahead/behind snapshot.
+ const actionsBlocked = syncBusy || !branchConfirmed || !aheadBehindConfirmed;
const handlePull = useCallback(async () => {
if (syncBusy || !workingDirectory) return;
@@ -226,12 +255,16 @@ const Overview = memo<OverviewProps>(
const showAhead = !!aheadBehind?.hasUpstream && aheadBehind.ahead > 0;
const showBehind = !!aheadBehind?.hasUpstream && aheadBehind.behind > 0;
+ // The branch picker routes through the worktree list, so both reads must be
+ // confirmed before either picker may act on them.
+ const pickersReady = branchConfirmed && worktreesConfirmed;
+ const canSwitchBranch = !detached && !!agentId && !!workingDirectory && pickersReady;
const branchRow = (
<OverviewRow
icon={GitBranchIcon}
- interactive={!detached && !!agentId && !!workingDirectory}
+ interactive={canSwitchBranch}
title={detached ? tDevice('workingDirectory.detachedHead', { sha: branch ?? '' }) : branch}
- trailing={!detached && agentId ? <PickerGlyph /> : undefined}
+ trailing={canSwitchBranch ? <PickerGlyph /> : undefined}
value={
detached ? (
<>
@@ -248,7 +281,7 @@ const Overview = memo<OverviewProps>(
const gitRows = (
<>
{branch &&
- (!detached && agentId && workingDirectory ? (
+ (canSwitchBranch ? (
<BranchSwitcher
agentId={agentId}
currentBranch={branch}
@@ -283,7 +316,7 @@ const Overview = memo<OverviewProps>(
<span className={rowStyles.rowAction}>{t('workingPanel.overview.sync.pull')}</span>
)
}
- onClick={syncBusy ? undefined : handlePull}
+ onClick={actionsBlocked ? undefined : handlePull}
/>
)}
{showAhead && (
@@ -299,7 +332,7 @@ const Overview = memo<OverviewProps>(
<span className={rowStyles.rowAction}>{t('workingPanel.overview.sync.push')}</span>
)
}
- onClick={syncBusy ? undefined : handlePush}
+ onClick={actionsBlocked ? undefined : handlePush}
/>
)}
@@ -309,6 +342,7 @@ const Overview = memo<OverviewProps>(
currentBranch={branch}
detached={detached}
deviceId={deviceId}
+ disabled={!pickersReady}
isGithub={isGithub}
path={workingDirectory}
placement={'bottomLeft'}
@@ -317,10 +351,10 @@ const Overview = memo<OverviewProps>(
onWorktreesChange={mutateWorktrees}
>
<OverviewRow
- interactive
icon={GitForkIcon}
+ interactive={pickersReady}
title={sourcePath ?? workingDirectory}
- trailing={<PickerGlyph />}
+ trailing={pickersReady ? <PickerGlyph /> : undefined}
value={t('workingPanel.overview.worktree.of', {
name: pathBasename(sourcePath ?? workingDirectory),
})}
@@ -331,7 +365,9 @@ const Overview = memo<OverviewProps>(
<OverviewRow
icon={ClipboardListIcon}
trailing={
- changeStats.files > 0 ? (
+ changesPending ? (
+ <RingLoadingIcon size={12} />
+ ) : changeStats.files > 0 ? (
<>
<span className={rowStyles.changeAdditions}>+{changeStats.additions}</span>
<span className={rowStyles.changeDeletions}>−{changeStats.deletions}</span>
diff --git a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
index 7df75a6b975..a691f1a8621 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
@@ -72,3 +72,17 @@ export const getStatusDeviceId = (
target: DeviceExecutionTarget,
boundDeviceId: string | undefined,
): string | undefined => (target === 'device' || target === 'local' ? boundDeviceId : undefined);
+
+/**
+ * The git section skeleton is a first-ever-load affordance only. Once any git
+ * read has data — live, or hydrated from the replica's persisted rows on
+ * reload — the rows render stale-first and the in-flight reads refresh them in
+ * place.
+ */
+export const shouldShowGitSkeleton = ({
+ hasData,
+ loading,
+}: {
+ hasData: boolean;
+ loading: boolean;
+}): boolean => loading && !hasData;
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
index 890e5b39364..d27177d8ccc 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
@@ -11,7 +11,12 @@ const mutate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const toastError = vi.hoisted(() => vi.fn());
vi.mock('@/services/git', () => ({ gitService: { pushGitBranch, runPullRequestAction } }));
+const revalidateGitStatus = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
vi.mock('@/libs/swr', () => ({ mutate }));
+vi.mock('@/store/device/gitStatus/store', () => ({
+ useGitStatusStore: { getState: () => ({ revalidateGitStatus }) },
+}));
vi.mock('@lobehub/ui', () => ({ toast: { error: toastError } }));
const params = { deviceId: 'dev-1', number: 7, workingDirectory: '/repo' };
@@ -74,8 +79,10 @@ describe('usePullRequestActions', () => {
expect(mutateDetail).toHaveBeenCalledTimes(1);
expect(mutate).toHaveBeenCalledWith(deviceKeys.gitPullRequestActivity('dev-1', '/repo', 7));
- expect(mutate).toHaveBeenCalledWith(deviceKeys.gitAheadBehind('dev-1', '/repo'));
- expect(mutate).toHaveBeenCalledWith(deviceKeys.gitWorkingTreeStatus('dev-1', '/repo'));
+ expect(revalidateGitStatus).toHaveBeenCalledWith('dev-1', '/repo', [
+ 'aheadBehind',
+ 'workingTreeStatus',
+ ]);
const matcher = mutate.mock.calls.find(([key]) => typeof key === 'function')?.[0];
expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/repo', 'feat/x', 7))).toBe(true);
expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/other', 'feat/x'))).toBe(false);
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
index c4f3b910faa..d8b42f50669 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
@@ -5,6 +5,7 @@ import { useCallback, useRef, useState } from 'react';
import { mutate } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
import { gitService } from '@/services/git';
+import { useGitStatusStore } from '@/store/device/gitStatus/store';
export type PullRequestBusy = DeviceGitPullRequestAction['type'] | 'push';
@@ -72,8 +73,9 @@ export const usePullRequestActions = ({
key[2] === workingDirectory &&
key[3] === number,
),
- mutate(deviceKeys.gitAheadBehind(cacheDeviceId, workingDirectory)),
- mutate(deviceKeys.gitWorkingTreeStatus(cacheDeviceId, workingDirectory)),
+ useGitStatusStore
+ .getState()
+ .revalidateGitStatus(deviceId, workingDirectory, ['aheadBehind', 'workingTreeStatus']),
]);
return true;
} catch (err) {
diff --git a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
index b14043c7ceb..13c91f79b73 100644
--- a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
@@ -20,6 +20,12 @@ vi.mock('@/libs/swr', () => ({
useClientDataSWR: vi.fn(() => ({ data: undefined })),
}));
+const revalidateGitStatus = vi.hoisted(() => vi.fn());
+
+vi.mock('@/store/device/gitStatus/store', () => ({
+ useGitStatusStore: { getState: () => ({ revalidateGitStatus }) },
+}));
+
vi.mock('@/services/git', () => ({
gitService: {
getGitBranchDiff: vi.fn(),
@@ -92,9 +98,11 @@ describe('useReviewPatches', () => {
'branch',
'origin/canary',
]);
- expect(mutate).toHaveBeenNthCalledWith(2, ['device:gitWorkingTreeStatus', 'device-1', '/repo']);
- expect(mutate).toHaveBeenNthCalledWith(3, ['device:gitAheadBehind', 'device-1', '/repo']);
- expect(mutate).toHaveBeenNthCalledWith(4, [
+ expect(revalidateGitStatus).toHaveBeenCalledWith('device-1', '/repo', [
+ 'workingTreeStatus',
+ 'aheadBehind',
+ ]);
+ expect(mutate).toHaveBeenNthCalledWith(2, [
'localFile:gitWorkingTreeFiles',
'device-1',
'/repo',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 94b642eec2c..24328cb543b 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -523,16 +523,6 @@ export const deviceKeys = {
workspaceId,
deviceId,
]),
- gitAheadBehind: def('device:gitAheadBehind', (deviceId: string, path: string) => [
- 'device:gitAheadBehind',
- 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,
@@ -592,16 +582,6 @@ export const deviceKeys = {
baseRef,
],
),
- gitWorkingTreeStatus: def('device:gitWorkingTreeStatus', (deviceId: string, path: string) => [
- 'device:gitWorkingTreeStatus',
- deviceId,
- path,
- ]),
- gitWorktrees: def('device:gitWorktrees', (deviceId: string, path: string) => [
- 'device:gitWorktrees',
- deviceId,
- path,
- ]),
listDevices: def('device:listDevices', () => ['device:listDevices']),
repoType: def('device:repoType', (path: string) => ['device:repoType', path]),
};
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 95218291426..15c1baefa25 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -3,6 +3,8 @@ import type {
GitWorkingTreePatch,
SubmoduleWorkingTreePatches,
} from '@lobechat/electron-client-ipc';
+import type { ReplicaOptimisticToken } from '@lobechat/replica';
+import type { ReplicaSlice, ReplicaSyncSchedule } from '@lobechat/replica/zustand';
import type {
DeviceGitAheadBehind,
DeviceGitPullRequestActivity,
@@ -12,11 +14,20 @@ import type {
DeviceGitWorkingTreeStatus,
DeviceGitWorktreeListItem,
} from '@lobechat/types';
+import { useCallback, useMemo, useRef } from 'react';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { deviceKeys, localFileKeys } from '@/libs/swr/keys';
import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/services/git';
+import {
+ type GitDiffStats,
+ gitStatusKey,
+ type GitStatusParams,
+ type GitStatusRead,
+} from './gitStatus/projection';
+import { type GitStatusStore, useGitStatusStore } from './gitStatus/store';
+
export type ReviewMode = 'unstaged' | 'branch';
const UNSTAGED_REVIEW_REFRESH_INTERVAL = 10 * 1000;
@@ -99,8 +110,9 @@ export const invalidateGitReviewCaches = async ({
const cacheDeviceId = deviceId ?? 'local';
await Promise.all([
mutate(deviceKeys.gitReviewPatches(cacheDeviceId, dirPath, mode, baseRef ?? '')),
- mutate(deviceKeys.gitWorkingTreeStatus(cacheDeviceId, dirPath)),
- mutate(deviceKeys.gitAheadBehind(cacheDeviceId, dirPath)),
+ useGitStatusStore
+ .getState()
+ .revalidateGitStatus(deviceId, dirPath, ['workingTreeStatus', 'aheadBehind']),
mutate(localFileKeys.gitWorkingTreeFiles(deviceId, dirPath)),
]);
};
@@ -132,19 +144,160 @@ export const useReviewPatches = (
);
};
+interface GitStatusReadResult<T> {
+ data: T | undefined;
+ error: unknown;
+ /**
+ * The current probe answered. A row hydrated from storage (or an optimistic
+ * write) is good enough to paint, but not to act on: the device read is the
+ * only thing that proves the persisted branch still exists.
+ */
+ isConfirmed: boolean;
+ /** Nothing to paint yet (no persisted row, no response) and a read is pending. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /**
+ * SWR-shaped: no argument re-runs the read; a value starts an optimistic
+ * overlay (memory only, never persisted) and, unless `revalidate: false`,
+ * re-runs the read that settles it.
+ */
+ mutate: (data?: T, options?: { revalidate?: boolean }) => Promise<unknown>;
+ /** Confirmed local write (persisted): for derived data a sibling read owns. */
+ set: (data: T) => void;
+}
+
+type GitStatusSlice<T> = Pick<
+ ReplicaSlice<GitStatusStore, GitStatusParams, GitStatusRead<T>, any>,
+ 'beginOptimistic' | 'fetch' | 'revalidate' | 'update' | 'useSync'
+>;
+
+/**
+ * Read one of the replica-backed git status reads (see `./gitStatus`): the
+ * persisted row paints first, the device read confirms it in the background.
+ * Returns the SWR-like shape the git chips were written against.
+ */
+const useGitStatusRead = <T>(
+ slice: GitStatusSlice<T>,
+ selectMap: (state: GitStatusStore) => Record<string, GitStatusRead<T>>,
+ selectEntries: (state: GitStatusStore) => Record<string, { source?: string } | undefined>,
+ deviceId: string | undefined,
+ path: string | undefined,
+ schedule: ReplicaSyncSchedule,
+): GitStatusReadResult<T> => {
+ const params = useMemo(
+ () => (isEnabled(deviceId, path) ? { deviceId, path } : null),
+ [deviceId, path],
+ );
+ const key = params ? gitStatusKey(params) : undefined;
+ const stored = useGitStatusStore((s) => (key ? selectMap(s)[key] : undefined));
+ // Only a head response makes the row authoritative (`source: 'server'`); a
+ // hydrated or optimistic row is a paint-only stand-in. Consumers use this to
+ // gate checkout / pull / push and the dead-directory hand-off.
+ const isConfirmed = useGitStatusStore((s) => !!key && selectEntries(s)[key]?.source === 'server');
+ // The driver forwards SWR options as given: a failed git read (dead path,
+ // unreachable device) is not retried, like the SWR hooks these replaced.
+ const syncOptions = { ...schedule, shouldRetryOnError: false };
+ const { error, isHydrated, isValidating, revalidate } = slice.useSync(params, syncOptions);
+
+ /**
+ * An optimistic write whose probe has not settled yet. Overlays are rebased
+ * onto every server response and are never persisted, so a read that started
+ * before the checkout cannot repaint the previous branch.
+ */
+ const optimistic = useRef<{
+ key: string;
+ token: ReplicaOptimisticToken<GitStatusRead<T>>;
+ } | null>(null);
+
+ const mutate = useCallback(
+ async (data?: T, options?: { revalidate?: boolean }) => {
+ if (!key) return;
+ if (data !== undefined) {
+ // The checkout can fail, or the app can close before `onAfterCheckout`
+ // revalidates: keep the value in an overlay so the next launch paints
+ // the confirmed branch, not one that never landed.
+ optimistic.current = {
+ key,
+ token: slice.beginOptimistic(key, (current) => ({ ...current, value: data })),
+ };
+ }
+ if (data === undefined || options?.revalidate !== false) {
+ const pending = optimistic.current;
+ if (pending && params) {
+ // A fresh read, not `revalidate`: a pre-checkout request may still be
+ // in flight, and its response would settle the overlay back to the
+ // branch the user just left.
+ try {
+ await slice.fetch(params, { fresh: true });
+ } catch {
+ // Keep the confirmed base; a later read repairs an unreachable device.
+ } finally {
+ // The head response already persisted the confirmed value. Roll back
+ // to it: committing would re-apply the optimistic mutation to the
+ // base, so a FAILED checkout would be re-persisted as if it landed.
+ if (optimistic.current === pending) {
+ pending.token.rollback();
+ optimistic.current = null;
+ }
+ }
+ return;
+ }
+ await revalidate();
+ }
+ },
+ [key, slice, revalidate],
+ );
+
+ const set = useCallback(
+ (data: T) => {
+ if (!key) return;
+ // Confirmed by the read that produced it (the review patches), so it is
+ // allowed to replace and persist the row.
+ slice.update(key, () => ({ value: data }));
+ },
+ [key, slice],
+ );
+
+ return {
+ data: stored?.value,
+ error,
+ isConfirmed,
+ isLoading: !!params && stored === undefined && !error && (!isHydrated || isValidating),
+ isValidating,
+ mutate,
+ set,
+ };
+};
+
+const selectBranchMap = (s: GitStatusStore) => s.gitBranchMap;
+const selectAheadBehindMap = (s: GitStatusStore) => s.gitAheadBehindMap;
+const selectWorkingTreeStatusMap = (s: GitStatusStore) => s.gitWorkingTreeStatusMap;
+const selectWorktreesMap = (s: GitStatusStore) => s.gitWorktreesMap;
+
+const selectDiffStatsMap = (s: GitStatusStore) => s.gitDiffStatsMap;
+
+const selectBranchEntries = (s: GitStatusStore) => s.gitBranchReplica.entries;
+const selectAheadBehindEntries = (s: GitStatusStore) => s.gitAheadBehindReplica.entries;
+const selectDiffStatsEntries = (s: GitStatusStore) => s.gitDiffStatsReplica.entries;
+const selectWorkingTreeStatusEntries = (s: GitStatusStore) => s.gitWorkingTreeStatusReplica.entries;
+const selectWorktreesEntries = (s: GitStatusStore) => s.gitWorktreesReplica.entries;
+
/**
* 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
+ * promptly. A longer window would swallow the 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 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 },
+ useGitStatusRead<GitBranchSummary>(
+ useGitStatusStore.getState().slices.branch,
+ selectBranchMap,
+ selectBranchEntries,
+ deviceId,
+ path,
+ { dedupingInterval: 2 * 1000 },
);
/**
@@ -169,15 +322,33 @@ export const useFetchGitLinkedPR = (
{ dedupingInterval: 60 * 1000, focusThrottleInterval: 60 * 1000, shouldRetryOnError: false },
);
+/**
+ * Compact uncommitted-diff counts for the composer's `+N −M` chip. There is no
+ * read of its own: the review-patch hook writes the counts here once they load,
+ * so a reload paints the previous session's chip before the diff is fetched.
+ */
+export const useFetchGitDiffStats = (deviceId: string | undefined, path?: string) =>
+ useGitStatusRead<GitDiffStats>(
+ useGitStatusStore.getState().slices.diffStats,
+ selectDiffStatsMap,
+ selectDiffStatsEntries,
+ deviceId,
+ path,
+ {},
+ );
+
/**
* Working-tree dirty-file counts. Revalidates on focus (5s throttle) so the
* +N ~M -K badge tracks edits when the user switches back to the window.
*/
export const useFetchGitWorkingTreeStatus = (deviceId: string | undefined, path?: string) =>
- useClientDataSWR<DeviceGitWorkingTreeStatus | undefined>(
- isEnabled(deviceId, path) ? deviceKeys.gitWorkingTreeStatus(deviceId ?? 'local', path) : null,
- () => gitService.getGitWorkingTreeStatus({ deviceId, path: path! }),
- { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
+ useGitStatusRead<DeviceGitWorkingTreeStatus>(
+ useGitStatusStore.getState().slices.workingTreeStatus,
+ selectWorkingTreeStatusMap,
+ selectWorkingTreeStatusEntries,
+ deviceId,
+ path,
+ { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true },
);
/**
@@ -185,10 +356,13 @@ export const useFetchGitWorkingTreeStatus = (deviceId: string | undefined, path?
* inside the read, so focus revalidation (5s throttle) surfaces remote updates.
*/
export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: string) =>
- useClientDataSWR<DeviceGitAheadBehind | undefined>(
- isEnabled(deviceId, path) ? deviceKeys.gitAheadBehind(deviceId ?? 'local', path) : null,
- () => gitService.getGitAheadBehind({ deviceId, path: path! }),
- { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
+ useGitStatusRead<DeviceGitAheadBehind>(
+ useGitStatusStore.getState().slices.aheadBehind,
+ selectAheadBehindMap,
+ selectAheadBehindEntries,
+ deviceId,
+ path,
+ { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true },
);
/**
@@ -197,10 +371,13 @@ export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: stri
* without restarting the conversation.
*/
export const useFetchGitWorktrees = (deviceId: string | undefined, path?: string) =>
- useClientDataSWR<DeviceGitWorktreeListItem[]>(
- isEnabled(deviceId, path) ? deviceKeys.gitWorktrees(deviceId ?? 'local', path) : null,
- () => gitService.listGitWorktrees({ deviceId, path: path! }),
- { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
+ useGitStatusRead<DeviceGitWorktreeListItem[]>(
+ useGitStatusStore.getState().slices.worktrees,
+ selectWorktreesMap,
+ selectWorktreesEntries,
+ deviceId,
+ path,
+ { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true },
);
export const pullRequestDetailRefreshInterval = (
diff --git a/src/store/device/gitStatus/projection.ts b/src/store/device/gitStatus/projection.ts
new file mode 100644
index 00000000000..442e07e9b23
--- /dev/null
+++ b/src/store/device/gitStatus/projection.ts
@@ -0,0 +1,108 @@
+import type {
+ DeviceGitAheadBehind,
+ DeviceGitWorkingTreeStatus,
+ DeviceGitWorktreeListItem,
+} from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+import type { GitBranchSummary } from '@/services/git';
+
+/**
+ * The small per-(device, directory) git reads behind the Working Sidebar
+ * Overview and the chat-input git chips. They are replicas so a reload paints
+ * the last branch / ahead-behind / dirty counts / worktrees on the first frame
+ * and the device read only confirms them.
+ *
+ * Only branch / upstream / count shapes are kept — no diffs, no credentials.
+ * Rows are partitioned by the cache scope (user + workspace) and keyed by
+ * device + path, so two devices that share a path never paint each other's
+ * state.
+ */
+export interface GitStatusParams {
+ /** Remote device; `undefined` reads this machine over Electron IPC. */
+ deviceId?: string;
+ path: string;
+}
+
+/** `local` stands for this machine, like the SWR device keys. */
+export const gitStatusKey = ({ deviceId, path }: GitStatusParams) =>
+ `${deviceId ?? 'local'}\u0000${path}`;
+
+/**
+ * One answered read. The value is wrapped so a read that answered with nothing
+ * (no upstream, unreachable device: `value` absent) still replaces a stale
+ * persisted row — a bare `undefined` / `null` response would leave it in place.
+ */
+export interface GitStatusRead<T> {
+ value?: T;
+}
+
+/**
+ * Line/file counts of the uncommitted diff — the numbers behind the composer's
+ * `+N −M` chip. Derived from the review patches, but only the compact counts are
+ * kept: no patch text, no file contents.
+ */
+export interface GitDiffStats {
+ additions: number;
+ deletions: number;
+ files: number;
+}
+
+/**
+ * Directories a user works in; old ones fall out of storage, not out of the
+ * app. Capped at the P0 git-overlay budget (20 per resource, LRU-evicted).
+ */
+const persist = { maxEntries: 20 };
+
+export const gitBranchResource = defineReplica<GitStatusParams, GitStatusRead<GitBranchSummary>>({
+ key: gitStatusKey,
+ name: 'deviceGitBranch',
+ persist,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export const gitAheadBehindResource = defineReplica<
+ GitStatusParams,
+ GitStatusRead<DeviceGitAheadBehind>
+>({
+ key: gitStatusKey,
+ name: 'deviceGitAheadBehind',
+ persist,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export const gitWorkingTreeStatusResource = defineReplica<
+ GitStatusParams,
+ GitStatusRead<DeviceGitWorkingTreeStatus>
+>({
+ key: gitStatusKey,
+ name: 'deviceGitWorkingTreeStatus',
+ persist,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export const gitWorktreesResource = defineReplica<
+ GitStatusParams,
+ GitStatusRead<DeviceGitWorktreeListItem[]>
+>({
+ key: gitStatusKey,
+ name: 'deviceGitWorktrees',
+ persist,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Memory + storage only: the counts are written from the review-patch read
+ * (a sibling resource), so there is no fetcher of its own to run.
+ */
+export const gitDiffStatsResource = defineReplica<GitStatusParams, GitStatusRead<GitDiffStats>>({
+ key: gitStatusKey,
+ name: 'deviceGitDiffStats',
+ persist,
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/device/gitStatus/store.test.ts b/src/store/device/gitStatus/store.test.ts
new file mode 100644
index 00000000000..bfa1a22d65a
--- /dev/null
+++ b/src/store/device/gitStatus/store.test.ts
@@ -0,0 +1,403 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The Overview / chat-input git reads are replicas: after a reload the last
+ * branch, ahead/behind counts, dirty counts and worktrees paint from the
+ * persisted copy on the first frame, and the device read only confirms them.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { gitService } from '@/services/git';
+
+import {
+ useFetchGitAheadBehind,
+ useFetchGitBranch,
+ useFetchGitDiffStats,
+ useFetchGitWorkingTreeStatus,
+ useFetchGitWorktrees,
+} from '../gitHooks';
+import {
+ gitAheadBehindResource,
+ gitBranchResource,
+ gitDiffStatsResource,
+ gitStatusKey,
+ gitWorkingTreeStatusResource,
+ gitWorktreesResource,
+} from './projection';
+import { initialGitStatusState, useGitStatusStore } from './store';
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isDesktop: true,
+}));
+
+vi.mock('@/services/git', () => ({
+ gitService: {
+ getGitAheadBehind: vi.fn(),
+ getGitBranch: vi.fn(),
+ getGitWorkingTreeStatus: vi.fn(),
+ listGitWorktrees: vi.fn(),
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+/** Never-resolving read: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+};
+
+const RESOURCES = [
+ gitBranchResource,
+ gitAheadBehindResource,
+ gitDiffStatsResource,
+ gitWorkingTreeStatusResource,
+ gitWorktreesResource,
+] as const;
+
+const REMOTE = { deviceId: 'device-1', path: '/repo' };
+const LOCAL = { deviceId: undefined, path: '/repo' };
+
+describe('git status replicas', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+ const seed = (resource: (typeof RESOURCES)[number], params: typeof REMOTE, data: unknown) =>
+ resource.storage!.set(
+ { queryKey: resource.storageKey(params), scope },
+ { data: { value: data } as any, updatedAt: 1 },
+ );
+
+ beforeEach(() => {
+ useScope(`git-user-${randomUUID()}:personal`);
+ act(() => useGitStatusStore.setState(initialGitStatusState));
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ RESOURCES.flatMap((resource) =>
+ [REMOTE, LOCAL].map((params) =>
+ resource.storage!.remove({ queryKey: resource.storageKey(params), scope: value }),
+ ),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ // Regression: these reads lived only in SWR's memory cache, so after a reload
+ // the Overview showed a skeleton and the chat-input branch chip popped in.
+ it('paints every persisted git read before the device answers', async () => {
+ await Promise.all([
+ seed(gitBranchResource, REMOTE, { branch: 'feat/cached', detached: false }),
+ seed(gitAheadBehindResource, REMOTE, { ahead: 2, behind: 0 }),
+ seed(gitWorkingTreeStatusResource, REMOTE, { added: 0, deleted: 0, modified: 2 }),
+ seed(gitWorktreesResource, REMOTE, [{ branch: 'feat/wt', path: '/repo-wt' }]),
+ ]);
+ vi.mocked(gitService.getGitBranch).mockImplementation(pending);
+ vi.mocked(gitService.getGitAheadBehind).mockImplementation(pending);
+ vi.mocked(gitService.getGitWorkingTreeStatus).mockImplementation(pending);
+ vi.mocked(gitService.listGitWorktrees).mockImplementation(pending);
+
+ const { result } = renderHook(
+ () => ({
+ aheadBehind: useFetchGitAheadBehind('device-1', '/repo'),
+ branch: useFetchGitBranch('device-1', '/repo'),
+ status: useFetchGitWorkingTreeStatus('device-1', '/repo'),
+ worktrees: useFetchGitWorktrees('device-1', '/repo'),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.branch.data?.branch).toBe('feat/cached'));
+ expect(result.current.aheadBehind.data).toMatchObject({ ahead: 2 });
+ expect(result.current.status.data).toMatchObject({ modified: 2 });
+ expect(result.current.worktrees.data).toEqual([{ branch: 'feat/wt', path: '/repo-wt' }]);
+ // A persisted row is something to paint: no skeleton while the read is pending.
+ expect(result.current.branch.isLoading).toBe(false);
+ expect(result.current.branch.isValidating).toBe(true);
+ // …but it is NOT confirmation: this session's probe has not answered yet, so
+ // checkout / pull / push and the dead-directory hand-off stay gated.
+ expect(result.current.branch.isConfirmed).toBe(false);
+ expect(gitService.getGitBranch).toHaveBeenCalledWith(REMOTE);
+ });
+
+ it('confirms a hydrated row only once the probe answers, including an empty answer', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'feat/cached', detached: false });
+ // `{}` is what `getGitBranch` resolves for a path it cannot read: an answer,
+ // and the only thing allowed to declare the directory gone.
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({});
+
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ expect(result.current.data).toEqual({});
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('replaces the persisted row with the device read and persists the new value', async () => {
+ await seed(gitBranchResource, LOCAL, { branch: 'old' });
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'new', detached: false });
+
+ const { result } = renderHook(() => useFetchGitBranch(undefined, '/repo'), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.branch).toBe('new'));
+ expect(result.current.isConfirmed).toBe(true);
+ await waitFor(async () =>
+ expect(
+ (
+ await gitBranchResource.storage!.get({
+ queryKey: gitBranchResource.storageKey(LOCAL),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { branch: 'new', detached: false } }),
+ );
+ });
+
+ it('keys rows by device and path, so another device never paints this one', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'remote-branch' });
+ vi.mocked(gitService.getGitBranch).mockImplementation(pending);
+
+ const { result } = renderHook(() => useFetchGitBranch(undefined, '/repo'), { wrapper });
+ // Let the (empty) local hydrate settle.
+ await waitFor(() => expect(gitService.getGitBranch).toHaveBeenCalledWith(LOCAL));
+
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+ expect(gitStatusKey(REMOTE)).not.toBe(gitStatusKey(LOCAL));
+ });
+
+ it('does not paint another identity’s rows', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'theirs' });
+ useScope(`git-user-${randomUUID()}:personal`);
+ vi.mocked(gitService.getGitBranch).mockImplementation(pending);
+
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(gitService.getGitBranch).toHaveBeenCalled());
+
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it('does not paint the same user’s rows from another workspace', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'workspace-one' });
+ useScope(scope.replace(':personal', ':workspace-two'));
+ vi.mocked(gitService.getGitBranch).mockImplementation(pending);
+
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(gitService.getGitBranch).toHaveBeenCalled());
+
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it('lets an empty answer replace a stale persisted row', async () => {
+ await seed(gitAheadBehindResource, REMOTE, { ahead: 5, behind: 1 });
+ vi.mocked(gitService.getGitAheadBehind).mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useFetchGitAheadBehind('device-1', '/repo'), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(useGitStatusStore.getState().gitAheadBehindMap[gitStatusKey(REMOTE)]).toEqual({}),
+ );
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('writes an optimistic branch through mutate without refetching, and never persists it', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'main', detached: false });
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'main', detached: false });
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(result.current.data?.branch).toBe('main'));
+ vi.mocked(gitService.getGitBranch).mockClear();
+
+ await act(() =>
+ result.current.mutate({ branch: 'feat/x', detached: false }, { revalidate: false }),
+ );
+
+ expect(result.current.data?.branch).toBe('feat/x');
+ expect(gitService.getGitBranch).not.toHaveBeenCalled();
+
+ // Review P2: an optimistic checkout value must stay in memory. If the
+ // checkout fails — or the renderer closes before `onAfterCheckout` runs —
+ // the next launch has to paint the confirmed branch, not `feat/x`.
+ expect(
+ (
+ await gitBranchResource.storage!.get({
+ queryKey: gitBranchResource.storageKey(REMOTE),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { branch: 'main', detached: false } });
+ });
+
+ // Review P2: a read that started before the checkout must not repaint the old
+ // branch. The optimistic write is an overlay (rebased onto server responses),
+ // not a confirmed write that an older response can overwrite.
+ it('keeps an optimistic branch when a read that started earlier answers', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'main', detached: false });
+ const read = deferred<{ branch: string; detached: boolean }>();
+ vi.mocked(gitService.getGitBranch).mockReturnValue(read.promise);
+
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(result.current.data?.branch).toBe('main'));
+ await waitFor(() => expect(gitService.getGitBranch).toHaveBeenCalledTimes(1));
+
+ await act(() =>
+ result.current.mutate({ branch: 'feat/x', detached: false }, { revalidate: false }),
+ );
+ expect(result.current.data?.branch).toBe('feat/x');
+
+ // The pre-checkout read settles with the old branch.
+ await act(async () => {
+ read.resolve({ branch: 'main', detached: false });
+ await read.promise;
+ });
+
+ expect(result.current.data?.branch).toBe('feat/x');
+ // …and still nothing about the checkout reached persistent storage.
+ expect(
+ (
+ await gitBranchResource.storage!.get({
+ queryKey: gitBranchResource.storageKey(REMOTE),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { branch: 'main', detached: false } });
+ });
+
+ // The composer's `+N −M` chip is derived from review patches; only its compact
+ // counts are persisted, so a reload paints the chip instead of growing the
+ // cluster when the diff arrives.
+ it('paints persisted diff counts and persists a confirmed write', async () => {
+ await seed(gitDiffStatsResource, REMOTE, { additions: 4, deletions: 2, files: 2 });
+ const { result } = renderHook(() => useFetchGitDiffStats('device-1', '/repo'), { wrapper });
+
+ await waitFor(() =>
+ expect(result.current.data).toEqual({ additions: 4, deletions: 2, files: 2 }),
+ );
+ act(() => result.current.set({ additions: 0, deletions: 0, files: 0 }));
+ expect(result.current.data).toEqual({ additions: 0, deletions: 0, files: 0 });
+ await waitFor(async () =>
+ expect(
+ (
+ await gitDiffStatsResource.storage!.get({
+ queryKey: gitDiffStatsResource.storageKey(REMOTE),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { additions: 0, deletions: 0, files: 0 } }),
+ );
+ });
+
+ // Review P1: the settlement after a checkout must roll back to the confirmed
+ // base. Committing would re-apply the optimistic branch to the base, so a
+ // failed checkout would be persisted as if it had landed.
+ it('rolls the optimistic branch back when the probe still reports the old branch', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'main', detached: false });
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'main', detached: false });
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(result.current.data?.branch).toBe('main'));
+
+ await act(() =>
+ result.current.mutate({ branch: 'feat/x', detached: false }, { revalidate: false }),
+ );
+ expect(result.current.data?.branch).toBe('feat/x');
+
+ // `onAfterCheckout` revalidates regardless of success; the probe answers
+ // with the branch that is actually checked out.
+ await act(() => result.current.mutate());
+ expect(result.current.data?.branch).toBe('main');
+ expect(
+ (
+ await gitBranchResource.storage!.get({
+ queryKey: gitBranchResource.storageKey(REMOTE),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { branch: 'main', detached: false } });
+ });
+
+ it('keeps the new branch once the probe confirms it', async () => {
+ await seed(gitBranchResource, REMOTE, { branch: 'main', detached: false });
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'main', detached: false });
+ const { result } = renderHook(() => useFetchGitBranch('device-1', '/repo'), { wrapper });
+ await waitFor(() => expect(result.current.data?.branch).toBe('main'));
+
+ await act(() =>
+ result.current.mutate({ branch: 'feat/x', detached: false }, { revalidate: false }),
+ );
+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'feat/x', detached: false });
+
+ await act(() => result.current.mutate());
+ await waitFor(() => expect(result.current.data?.branch).toBe('feat/x'));
+ expect(
+ (
+ await gitBranchResource.storage!.get({
+ queryKey: gitBranchResource.storageKey(REMOTE),
+ scope,
+ })
+ )?.data,
+ ).toEqual({ value: { branch: 'feat/x', detached: false } });
+ });
+
+ it('revalidates the mounted reads of a directory', async () => {
+ vi.mocked(gitService.getGitAheadBehind).mockResolvedValue({ ahead: 0, behind: 0 } as any);
+ const { result } = renderHook(() => useFetchGitAheadBehind('device-1', '/repo'), {
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.data).toMatchObject({ ahead: 0 }));
+
+ vi.mocked(gitService.getGitAheadBehind).mockResolvedValue({ ahead: 3, behind: 0 } as any);
+ await act(() =>
+ useGitStatusStore.getState().revalidateGitStatus('device-1', '/repo', ['aheadBehind']),
+ );
+
+ await waitFor(() => expect(result.current.data).toMatchObject({ ahead: 3 }));
+ });
+
+ // The persistence moved to replicas: the SWR cache tiers must not also keep it.
+ it('is not persisted by the SWR cache layer', () => {
+ const patterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];
+ for (const name of ['gitBranch', 'gitAheadBehind', 'gitWorkingTreeStatus', 'gitWorktrees']) {
+ expect(patterns.some((pattern) => pattern.includes(name))).toBe(false);
+ }
+ });
+});
diff --git a/src/store/device/gitStatus/store.ts b/src/store/device/gitStatus/store.ts
new file mode 100644
index 00000000000..12862b55eaa
--- /dev/null
+++ b/src/store/device/gitStatus/store.ts
@@ -0,0 +1,164 @@
+import type {
+ DeviceGitAheadBehind,
+ DeviceGitWorkingTreeStatus,
+ DeviceGitWorktreeListItem,
+} from '@lobechat/types';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+import { type GitBranchSummary, gitService } from '@/services/git';
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+import {
+ gitAheadBehindResource,
+ gitBranchResource,
+ type GitDiffStats,
+ gitDiffStatsResource,
+ gitStatusKey,
+ type GitStatusParams,
+ type GitStatusRead,
+ gitWorkingTreeStatusResource,
+ gitWorktreesResource,
+} from './projection';
+
+export interface GitStatusStoreState {
+ /** `gitStatusKey(params)` → ahead/behind counts. */
+ gitAheadBehindMap: Record<string, GitStatusRead<DeviceGitAheadBehind>>;
+ gitAheadBehindReplica: ReplicaState<GitStatusRead<DeviceGitAheadBehind>>;
+ /** `gitStatusKey(params)` → current branch + detached + upstream. */
+ gitBranchMap: Record<string, GitStatusRead<GitBranchSummary>>;
+ gitBranchReplica: ReplicaState<GitStatusRead<GitBranchSummary>>;
+ /** `gitStatusKey(params)` → uncommitted diff line/file counts (composer chip). */
+ gitDiffStatsMap: Record<string, GitStatusRead<GitDiffStats>>;
+ gitDiffStatsReplica: ReplicaState<GitStatusRead<GitDiffStats>>;
+ /** `gitStatusKey(params)` → dirty-file counts. */
+ gitWorkingTreeStatusMap: Record<string, GitStatusRead<DeviceGitWorkingTreeStatus>>;
+ gitWorkingTreeStatusReplica: ReplicaState<GitStatusRead<DeviceGitWorkingTreeStatus>>;
+ /** `gitStatusKey(params)` → worktrees of the same repository. */
+ gitWorktreesMap: Record<string, GitStatusRead<DeviceGitWorktreeListItem[]>>;
+ gitWorktreesReplica: ReplicaState<GitStatusRead<DeviceGitWorktreeListItem[]>>;
+}
+
+export const initialGitStatusState: GitStatusStoreState = {
+ gitAheadBehindMap: {},
+ gitAheadBehindReplica: createReplicaState(),
+ gitBranchMap: {},
+ gitBranchReplica: createReplicaState(),
+ gitDiffStatsMap: {},
+ gitDiffStatsReplica: createReplicaState(),
+ gitWorkingTreeStatusMap: {},
+ gitWorkingTreeStatusReplica: createReplicaState(),
+ gitWorktreesMap: {},
+ gitWorktreesReplica: createReplicaState(),
+};
+
+export type GitStatusKind =
+ 'aheadBehind' | 'branch' | 'diffStats' | 'workingTreeStatus' | 'worktrees';
+
+const createSlices = (
+ set: (partial: Partial<GitStatusStore>, replace?: false, action?: any) => void,
+ get: () => GitStatusStore,
+) => ({
+ aheadBehind: createReplicaSlice(gitAheadBehindResource, {
+ actionPrefix: 'gitStatus/aheadBehind',
+ fetcher: async (params: GitStatusParams) => ({
+ value: await gitService.getGitAheadBehind(params),
+ }),
+ get,
+ set,
+ stateKey: 'gitAheadBehindReplica',
+ view: recordLens<GitStatusStore, GitStatusRead<DeviceGitAheadBehind>>('gitAheadBehindMap'),
+ }),
+ branch: createReplicaSlice(gitBranchResource, {
+ actionPrefix: 'gitStatus/branch',
+ fetcher: async (params: GitStatusParams) => ({ value: await gitService.getGitBranch(params) }),
+ get,
+ set,
+ stateKey: 'gitBranchReplica',
+ view: recordLens<GitStatusStore, GitStatusRead<GitBranchSummary>>('gitBranchMap'),
+ }),
+ // No fetcher: the counts are written from the review-patch read that already
+ // fetched them (see `useFetchGitDiffStats` + the GitStatus effect).
+ diffStats: createReplicaSlice(gitDiffStatsResource, {
+ actionPrefix: 'gitStatus/diffStats',
+ get,
+ set,
+ stateKey: 'gitDiffStatsReplica',
+ view: recordLens<GitStatusStore, GitStatusRead<GitDiffStats>>('gitDiffStatsMap'),
+ }),
+ workingTreeStatus: createReplicaSlice(gitWorkingTreeStatusResource, {
+ actionPrefix: 'gitStatus/workingTreeStatus',
+ fetcher: async (params: GitStatusParams) => ({
+ value: await gitService.getGitWorkingTreeStatus(params),
+ }),
+ get,
+ set,
+ stateKey: 'gitWorkingTreeStatusReplica',
+ view: recordLens<GitStatusStore, GitStatusRead<DeviceGitWorkingTreeStatus>>(
+ 'gitWorkingTreeStatusMap',
+ ),
+ }),
+ worktrees: createReplicaSlice(gitWorktreesResource, {
+ actionPrefix: 'gitStatus/worktrees',
+ fetcher: async (params: GitStatusParams) => ({
+ value: await gitService.listGitWorktrees(params),
+ }),
+ get,
+ set,
+ stateKey: 'gitWorktreesReplica',
+ view: recordLens<GitStatusStore, GitStatusRead<DeviceGitWorktreeListItem[]>>('gitWorktreesMap'),
+ }),
+});
+
+type GitStatusSlices = ReturnType<typeof createSlices>;
+
+export interface GitStatusStore extends GitStatusStoreState {
+ /**
+ * Re-run the mounted reads of one directory (all kinds by default) — after a
+ * pull / push / checkout / worktree change made outside the hooks' own views.
+ */
+ revalidateGitStatus: (
+ deviceId: string | undefined,
+ path: string,
+ kinds?: GitStatusKind[],
+ ) => Promise<void>;
+ /** @internal The replica slices; read through the hooks in `gitHooks.ts`. */
+ slices: GitStatusSlices;
+}
+
+const ALL_KINDS: GitStatusKind[] = [
+ 'aheadBehind',
+ 'branch',
+ 'diffStats',
+ 'workingTreeStatus',
+ 'worktrees',
+];
+
+const devtools = createDevtools('gitStatus');
+
+export const useGitStatusStore = createWithEqualityFn<GitStatusStore>()(
+ devtools((set, get) => {
+ const slices = createSlices(set, get);
+
+ return {
+ ...initialGitStatusState,
+ revalidateGitStatus: async (deviceId, path, kinds = ALL_KINDS) => {
+ const key = gitStatusKey({ deviceId, path });
+ await Promise.all(kinds.map((kind) => slices[kind].revalidate(key)));
+ },
+ slices,
+ };
+ }),
+ shallow,
+);
+
+expose('gitStatus', useGitStatusStore);
+
+export const getGitStatusStoreState = () => useGitStatusStore.getState();
diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
index cc921c7208f..439bf85a6aa 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
@@ -19,11 +19,8 @@ const gitServiceMocks = vi.hoisted(() => ({
listGitWorktrees: vi.fn(),
}));
-const swrMocks = vi.hoisted(() => ({
- mutate: vi.fn(),
-}));
-
-vi.mock('@/libs/swr', () => swrMocks);
+const gsMocks = vi.hoisted(() => ({ revalidateGitStatus: vi.fn() }));
+vi.mock('@/store/device/gitStatus/store', () => ({ getGitStatusStoreState: () => gsMocks }));
vi.mock('@/store/chat/store', () => ({
getChatStoreState: () => chatMocks,
@@ -318,7 +315,7 @@ describe('recordGitCommandEffects', () => {
await recordGitCommandEffects({ command: 'git switch fix/topic', topicId: 't1' });
- expect(swrMocks.mutate).toHaveBeenCalledWith(['device:gitBranch', 'local', '/repo']);
+ expect(gsMocks.revalidateGitStatus).toHaveBeenCalledWith(undefined, '/repo', ['branch']);
});
it('refreshes the remote-device branch cache after a branch switch', async () => {
@@ -337,7 +334,7 @@ describe('recordGitCommandEffects', () => {
await recordGitCommandEffects({ command: 'git switch fix/topic', topicId: 't1' });
- expect(swrMocks.mutate).toHaveBeenCalledWith(['device:gitBranch', 'remote-device', '/repo']);
+ expect(gsMocks.revalidateGitStatus).toHaveBeenCalledWith('remote-device', '/repo', ['branch']);
});
it('updates the topic branch when the agent switches branch with git switch', async () => {
@@ -1130,6 +1127,6 @@ describe('recordGitCommandEffects — git push', () => {
topicId: 't1',
});
- expect(swrMocks.mutate).toHaveBeenCalledWith(['device:gitBranch', 'local', '/repo']);
+ expect(gsMocks.revalidateGitStatus).toHaveBeenCalledWith(undefined, '/repo', ['branch']);
});
});
diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
index f12a9dcabdd..57fba367977 100644
--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts
+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
@@ -7,11 +7,10 @@ import type {
import { getWorkingDirSourcePath } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
-import { mutate } from '@/libs/swr';
-import { deviceKeys } from '@/libs/swr/keys';
import { gitService } from '@/services/git';
import { topicSelectors } from '@/store/chat/selectors';
import { getChatStoreState } from '@/store/chat/store';
+import { getGitStatusStoreState } from '@/store/device/gitStatus/store';
import { getElectronStoreState } from '@/store/electron';
/**
@@ -1078,7 +1077,8 @@ export const recordGitCommandEffects = async (params: {
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
const cacheDeviceId =
currentDeviceId && boundDeviceId === currentDeviceId ? 'local' : boundDeviceId;
- await mutate(deviceKeys.gitBranch(cacheDeviceId ?? 'local', source));
+ const revalidateDeviceId = cacheDeviceId === 'local' ? undefined : cacheDeviceId;
+ await getGitStatusStoreState().revalidateGitStatus(revalidateDeviceId, source, ['branch']);
}
};