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(working-sidebar): paint the Review and PR tabs stale-first after a reload (#20845)

Arvin Xuba6c5c903625
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx
index 741d05d89e2..12760a4b8b6 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx
@@ -147,103 +147,106 @@ const buildTimeline = (detail: DeviceGitPullRequestDetail): Entry[] =>
].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
interface ActivityTimelineProps {
+ actionsDisabled?: boolean;
busy?: PullRequestBusy;
detail: DeviceGitPullRequestDetail;
onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;
}
-const ActivityTimeline = memo<ActivityTimelineProps>(({ busy, detail, onAction }) => {
- const { t } = useTranslation('chat');
- const tr = t as unknown as TranslateKey;
- const [draft, setDraft] = useState('');
- const timeline = useMemo(() => buildTimeline(detail), [detail]);
-
- const submit = async () => {
- const body = draft.trim();
- if (!body) return;
- if (await onAction({ body, type: 'comment' })) setDraft('');
- };
-
- return (
- <>
- {timeline.map((entry) => {
- if (entry.kind === 'comment')
- return (
- <div className={styles.comment} key={entry.id}>
- <Flexbox horizontal align={'center'} className={styles.commentHead} gap={8}>
- <Avatar avatar={githubAvatar(entry.author)} size={18} />
- <strong>{entry.author}</strong>
- <span>{timeAgo(entry.at)}</span>
- </Flexbox>
- <div className={styles.commentBodyWrap}>
- <Markdown className={styles.commentBody} fontSize={13} variant={'chat'}>
- {entry.body}
- </Markdown>
+const ActivityTimeline = memo<ActivityTimelineProps>(
+ ({ actionsDisabled, busy, detail, onAction }) => {
+ const { t } = useTranslation('chat');
+ const tr = t as unknown as TranslateKey;
+ const [draft, setDraft] = useState('');
+ const timeline = useMemo(() => buildTimeline(detail), [detail]);
+
+ const submit = async () => {
+ const body = draft.trim();
+ if (!body) return;
+ if (await onAction({ body, type: 'comment' })) setDraft('');
+ };
+
+ return (
+ <>
+ {timeline.map((entry) => {
+ if (entry.kind === 'comment')
+ return (
+ <div className={styles.comment} key={entry.id}>
+ <Flexbox horizontal align={'center'} className={styles.commentHead} gap={8}>
+ <Avatar avatar={githubAvatar(entry.author)} size={18} />
+ <strong>{entry.author}</strong>
+ <span>{timeAgo(entry.at)}</span>
+ </Flexbox>
+ <div className={styles.commentBodyWrap}>
+ <Markdown className={styles.commentBody} fontSize={13} variant={'chat'}>
+ {entry.body}
+ </Markdown>
+ </div>
</div>
- </div>
+ );
+ const visual =
+ entry.kind === 'review'
+ ? REVIEW_VISUAL[entry.state]
+ : {
+ icon: GitCommitHorizontalIcon,
+ labelKey: 'workingPanel.pr.activity.committed',
+ tone: 'neutral' as Tone,
+ };
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.event}
+ gap={8}
+ key={entry.kind === 'commit' ? entry.sha : `review:${entry.author}:${entry.at}`}
+ >
+ <Icon
+ icon={visual.icon}
+ size={14}
+ style={visual.tone === 'neutral' ? undefined : { color: TONE_COLOR[visual.tone] }}
+ />
+ <span>
+ <strong>{entry.author}</strong> {tr(visual.labelKey)}{' '}
+ {entry.kind === 'commit' && (
+ <code
+ className={styles.sha}
+ onClick={() =>
+ void electronSystemService.openExternalLink(
+ `https://github.com/${detail.repo.owner}/${detail.repo.name}/pull/${detail.number}/commits/${entry.sha}`,
+ )
+ }
+ >
+ {entry.sha.slice(0, 7)}
+ </code>
+ )}{' '}
+ · {timeAgo(entry.at)}
+ </span>
+ </Flexbox>
);
- const visual =
- entry.kind === 'review'
- ? REVIEW_VISUAL[entry.state]
- : {
- icon: GitCommitHorizontalIcon,
- labelKey: 'workingPanel.pr.activity.committed',
- tone: 'neutral' as Tone,
- };
- return (
- <Flexbox
- horizontal
- align={'center'}
- className={styles.event}
- gap={8}
- key={entry.kind === 'commit' ? entry.sha : `review:${entry.author}:${entry.at}`}
- >
- <Icon
- icon={visual.icon}
- size={14}
- style={visual.tone === 'neutral' ? undefined : { color: TONE_COLOR[visual.tone] }}
- />
- <span>
- <strong>{entry.author}</strong> {tr(visual.labelKey)}{' '}
- {entry.kind === 'commit' && (
- <code
- className={styles.sha}
- onClick={() =>
- void electronSystemService.openExternalLink(
- `https://github.com/${detail.repo.owner}/${detail.repo.name}/pull/${detail.number}/commits/${entry.sha}`,
- )
- }
- >
- {entry.sha.slice(0, 7)}
- </code>
- )}{' '}
- · {timeAgo(entry.at)}
- </span>
+ })}
+ <Flexbox className={styles.composer} gap={6}>
+ <TextArea
+ autoSize={{ minRows: 1 }}
+ placeholder={t('workingPanel.pr.composer.placeholder')}
+ value={draft}
+ variant={'filled'}
+ onChange={(e) => setDraft(e.target.value)}
+ />
+ <Flexbox horizontal justify={'flex-end'}>
+ <Button
+ disabled={!draft.trim() || !!busy || actionsDisabled}
+ loading={busy === 'comment'}
+ size={'small'}
+ onClick={() => void submit()}
+ >
+ {t('workingPanel.pr.composer.submit')}
+ </Button>
</Flexbox>
- );
- })}
- <Flexbox className={styles.composer} gap={6}>
- <TextArea
- autoSize={{ minRows: 1 }}
- placeholder={t('workingPanel.pr.composer.placeholder')}
- value={draft}
- variant={'filled'}
- onChange={(e) => setDraft(e.target.value)}
- />
- <Flexbox horizontal justify={'flex-end'}>
- <Button
- disabled={!draft.trim() || !!busy}
- loading={busy === 'comment'}
- size={'small'}
- onClick={() => void submit()}
- >
- {t('workingPanel.pr.composer.submit')}
- </Button>
</Flexbox>
- </Flexbox>
- </>
- );
-});
+ </>
+ );
+ },
+);
ActivityTimeline.displayName = 'PullRequestActivityTimeline';
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx
index b96549f7815..83d251277a3 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx
@@ -18,6 +18,8 @@ import { rowStyles } from '../Overview/OverviewRow';
import PrHead, { headStyles, PrStatePill, PrTitle } from './Head';
interface HeaderProps {
+ /** Mutations (close / reopen / change base) wait for the live PR reads. */
+ actionsDisabled?: boolean;
activityLoaded?: boolean;
detail: DeviceGitPullRequestDetail;
deviceId?: string;
@@ -26,7 +28,7 @@ interface HeaderProps {
}
const Header = memo<HeaderProps>(
- ({ activityLoaded = true, detail, deviceId, onAction, workingDirectory }) => {
+ ({ actionsDisabled, activityLoaded = true, detail, deviceId, onAction, workingDirectory }) => {
const { t } = useTranslation('chat');
const canChangeBase = detail.viewerCanWrite && detail.state === 'open';
const [basePickerOpen, setBasePickerOpen] = useState(false);
@@ -41,6 +43,7 @@ const Header = memo<HeaderProps>(
.filter((name) => name !== detail.headRefName)
.map((name) => ({
key: name,
+ disabled: actionsDisabled,
label: name,
onClick: () => {
if (name !== detail.baseRefName) void onAction({ base: name, type: 'changeBase' });
@@ -66,11 +69,13 @@ const Header = memo<HeaderProps>(
detail.state === 'open'
? {
danger: true,
+ disabled: actionsDisabled,
key: 'close',
label: t('workingPanel.pr.menu.close'),
onClick: () => void onAction({ type: 'close' }),
}
: {
+ disabled: actionsDisabled,
key: 'reopen',
label: t('workingPanel.pr.menu.reopen'),
onClick: () => void onAction({ type: 'reopen' }),
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx
index 44e19b0af76..ec2777a218a 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx
@@ -191,6 +191,7 @@ const MergeDock = memo<MergeDockProps>(
{status.key === 'autoMerge' && (
<Button
className={styles.trailing}
+ disabled={contextLoading}
loading={busy === 'disableAutoMerge'}
size={'small'}
type={'text'}
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx
index bc7614752c4..59cff66dbaf 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx
@@ -21,7 +21,8 @@ import {
} from 'lucide-react';
import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { SWRResponse } from 'swr';
+
+import type { GitReplicaReadResult } from '@/store/device';
import { ChevronRight, OverviewRow, rowStyles } from '../Overview/OverviewRow';
import { sectionStyles } from '../Overview/sectionStyles';
@@ -98,8 +99,9 @@ const Section = memo<SectionProps>(({ children, count, onToggle, open = true, ti
Section.displayName = 'PullRequestSection';
interface SectionsProps {
+ actionsDisabled?: boolean;
activity: Pick<
- SWRResponse<DeviceGitPullRequestActivity>,
+ GitReplicaReadResult<DeviceGitPullRequestActivity>,
'data' | 'error' | 'isValidating' | 'mutate'
>;
busy?: PullRequestBusy;
@@ -108,119 +110,130 @@ interface SectionsProps {
onOpenTab: (tab: string) => void;
}
-const Sections = memo<SectionsProps>(({ activity, busy, detail, onAction, onOpenTab }) => {
- const { t } = useTranslation('chat');
- const { t: tCommon } = useTranslation('common');
- const activityPlaceholder = activity.error ? (
- <Flexbox gap={8}>
- <span>{t('workingPanel.pr.error.load')}</span>
- <Button loading={activity.isValidating} size={'small'} onClick={() => void activity.mutate()}>
- {tCommon('retry')}
- </Button>
- </Flexbox>
- ) : (
- <Skeleton.Text rows={3} />
- );
- const [open, setOpen] = useState({
- activity: true,
- checks: false,
- commits: false,
- description: true,
- });
- const toggle = (key: keyof typeof open) => () => setOpen((o) => ({ ...o, [key]: !o[key] }));
-
- const failing = detail.checks.filter(
- (check) => check.status === 'failure' || check.status === 'cancelled',
- ).length;
- const running = detail.checks.filter((check) => check.status === 'pending').length;
- const checksCount = failing ? (
- <span style={{ color: cssVar.colorError }}>
- {t('workingPanel.pr.checks.failing', { count: failing })}
- </span>
- ) : running ? (
- <span style={{ color: cssVar.colorWarning }}>
- {t('workingPanel.pr.checks.running', { count: running })}
- </span>
- ) : (
- detail.checks.length
- );
-
- return (
- <>
- {detail.body && (
+const Sections = memo<SectionsProps>(
+ ({ actionsDisabled, activity, busy, detail, onAction, onOpenTab }) => {
+ const { t } = useTranslation('chat');
+ const { t: tCommon } = useTranslation('common');
+ const activityPlaceholder = activity.error ? (
+ <Flexbox gap={8}>
+ <span>{t('workingPanel.pr.error.load')}</span>
+ <Button loading={activity.isValidating} onClick={() => void activity.mutate()}>
+ {tCommon('retry')}
+ </Button>
+ </Flexbox>
+ ) : (
+ <Skeleton.Text rows={3} />
+ );
+ const [open, setOpen] = useState({
+ activity: true,
+ checks: false,
+ commits: false,
+ description: true,
+ });
+ const toggle = (key: keyof typeof open) => () => setOpen((o) => ({ ...o, [key]: !o[key] }));
+
+ // Older devices (and persisted rows) may omit the list fields.
+ const checks = detail.checks ?? [];
+ const commits = detail.commits ?? [];
+ const activityCount = (detail.comments?.length ?? 0) + (detail.reviews?.length ?? 0);
+ const failing = checks.filter(
+ (check) => check.status === 'failure' || check.status === 'cancelled',
+ ).length;
+ const running = checks.filter((check) => check.status === 'pending').length;
+ const checksCount = failing ? (
+ <span style={{ color: cssVar.colorError }}>
+ {t('workingPanel.pr.checks.failing', { count: failing })}
+ </span>
+ ) : running ? (
+ <span style={{ color: cssVar.colorWarning }}>
+ {t('workingPanel.pr.checks.running', { count: running })}
+ </span>
+ ) : (
+ checks.length
+ );
+
+ return (
+ <>
+ {detail.body && (
+ <Section
+ open={open.description}
+ title={t('workingPanel.pr.section.description')}
+ onToggle={toggle('description')}
+ >
+ <Markdown className={styles.body} fontSize={13} variant={'chat'}>
+ {detail.body}
+ </Markdown>
+ </Section>
+ )}
+ <Section count={detail.changedFiles} title={t('workingPanel.pr.section.files')}>
+ <OverviewRow
+ icon={FolderOpenIcon}
+ value={t('workingPanel.pr.files.openReview')}
+ trailing={
+ <>
+ <span className={rowStyles.changeAdditions}>+{detail.additions}</span>
+ <span className={rowStyles.changeDeletions}>−{detail.deletions}</span>
+ <ChevronRight />
+ </>
+ }
+ onClick={() => onOpenTab('review')}
+ />
+ </Section>
+ {checks.length > 0 && (
+ <Section
+ count={checksCount}
+ open={open.checks}
+ title={t('workingPanel.pr.section.checks')}
+ onToggle={toggle('checks')}
+ >
+ <ChecksList checks={checks} />
+ </Section>
+ )}
<Section
- open={open.description}
- title={t('workingPanel.pr.section.description')}
- onToggle={toggle('description')}
+ count={activity.data ? commits.length : undefined}
+ open={open.commits}
+ title={t('workingPanel.pr.section.commits')}
+ onToggle={toggle('commits')}
>
- <Markdown className={styles.body} fontSize={13} variant={'chat'}>
- {detail.body}
- </Markdown>
+ {!activity.data
+ ? activityPlaceholder
+ : commits.map((commit) => (
+ <OverviewRow
+ weak
+ icon={GitCommitHorizontalIcon}
+ key={commit.sha}
+ title={commit.message}
+ value={commit.message.split('\n')[0]}
+ trailing={
+ <>
+ <span className={styles.sha}>{commit.sha.slice(0, 7)}</span>
+ {timeAgo(commit.committedAt)}
+ </>
+ }
+ />
+ ))}
</Section>
- )}
- <Section count={detail.changedFiles} title={t('workingPanel.pr.section.files')}>
- <OverviewRow
- icon={FolderOpenIcon}
- value={t('workingPanel.pr.files.openReview')}
- trailing={
- <>
- <span className={rowStyles.changeAdditions}>+{detail.additions}</span>
- <span className={rowStyles.changeDeletions}>−{detail.deletions}</span>
- <ChevronRight />
- </>
- }
- onClick={() => onOpenTab('review')}
- />
- </Section>
- {detail.checks.length > 0 && (
<Section
- count={checksCount}
- open={open.checks}
- title={t('workingPanel.pr.section.checks')}
- onToggle={toggle('checks')}
+ count={activity.data ? activityCount : undefined}
+ open={open.activity}
+ title={t('workingPanel.pr.section.activity')}
+ onToggle={toggle('activity')}
>
- <ChecksList checks={detail.checks} />
+ {activity.data ? (
+ <ActivityTimeline
+ actionsDisabled={actionsDisabled}
+ busy={busy}
+ detail={detail}
+ onAction={onAction}
+ />
+ ) : (
+ activityPlaceholder
+ )}
</Section>
- )}
- <Section
- count={activity.data ? detail.commits.length : undefined}
- open={open.commits}
- title={t('workingPanel.pr.section.commits')}
- onToggle={toggle('commits')}
- >
- {!activity.data
- ? activityPlaceholder
- : detail.commits.map((commit) => (
- <OverviewRow
- weak
- icon={GitCommitHorizontalIcon}
- key={commit.sha}
- title={commit.message}
- value={commit.message.split('\n')[0]}
- trailing={
- <>
- <span className={styles.sha}>{commit.sha.slice(0, 7)}</span>
- {timeAgo(commit.committedAt)}
- </>
- }
- />
- ))}
- </Section>
- <Section
- count={activity.data ? detail.comments.length + detail.reviews.length : undefined}
- open={open.activity}
- title={t('workingPanel.pr.section.activity')}
- onToggle={toggle('activity')}
- >
- {activity.data ? (
- <ActivityTimeline busy={busy} detail={detail} onAction={onAction} />
- ) : (
- activityPlaceholder
- )}
- </Section>
- </>
- );
-});
+ </>
+ );
+ },
+);
Sections.displayName = 'PullRequestSections';
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/actionLock.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/actionLock.test.ts
new file mode 100644
index 00000000000..c8b98a68e1a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/actionLock.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolvePullRequestActionLock } from '../actionLock';
+
+const context = {
+ baseBehindBy: 0,
+ requiredChecks: ['ci'],
+ viewerCanBypass: true,
+ viewerCanWrite: true,
+};
+const live = {
+ confirmed: true,
+ context,
+ contextConfirmed: true,
+ contextError: undefined,
+ detailConfirmed: true,
+ detailError: undefined,
+};
+
+describe('resolvePullRequestActionLock', () => {
+ it('unlocks once the PR and its merge context are live', () => {
+ expect(resolvePullRequestActionLock(live)).toEqual({
+ context,
+ contextLoading: false,
+ locked: false,
+ policyLocked: false,
+ refreshFailed: false,
+ });
+ });
+
+ it('locks every action until the PR itself is confirmed', () => {
+ expect(resolvePullRequestActionLock({ ...live, confirmed: false }).locked).toBe(true);
+ expect(resolvePullRequestActionLock({ ...live, detailConfirmed: false }).locked).toBe(true);
+ });
+
+ // Regression: a persisted merge context hydrated before its live read, so
+ // merge / update / bypass / base change unlocked on last session's policy.
+ it('paints a persisted merge context but locks policy actions until it is live', () => {
+ expect(resolvePullRequestActionLock({ ...live, contextConfirmed: false })).toEqual({
+ context,
+ contextLoading: true,
+ locked: false,
+ policyLocked: true,
+ refreshFailed: false,
+ });
+ });
+
+ it('drops the persisted policy instead of locking forever when the live read fails', () => {
+ expect(
+ resolvePullRequestActionLock({
+ ...live,
+ contextConfirmed: false,
+ contextError: new Error('gh failed'),
+ }),
+ ).toEqual({
+ context: undefined,
+ contextLoading: false,
+ locked: false,
+ policyLocked: false,
+ refreshFailed: true,
+ });
+ });
+
+ it('reports the merge context as loading only while its read is in flight', () => {
+ expect(
+ resolvePullRequestActionLock({
+ ...live,
+ context: undefined,
+ contextConfirmed: false,
+ }).contextLoading,
+ ).toBe(true);
+ });
+
+ // Regression: a failed refresh of a persisted detail kept every action locked
+ // with no error and no retry, since the error row only rendered without detail.
+ it('flags a failed live detail read while the persisted detail still paints', () => {
+ const result = resolvePullRequestActionLock({
+ ...live,
+ detailConfirmed: false,
+ detailError: new Error('gh failed'),
+ });
+ expect(result.locked).toBe(true);
+ expect(result.refreshFailed).toBe(true);
+ });
+
+ it('does not flag a failed refresh once the read was confirmed this session', () => {
+ expect(
+ resolvePullRequestActionLock({
+ ...live,
+ contextError: new Error('gh failed'),
+ detailError: new Error('gh failed'),
+ }).refreshFailed,
+ ).toBe(false);
+ });
+
+ it('keeps a confirmed context through a later failed refresh', () => {
+ expect(
+ resolvePullRequestActionLock({ ...live, contextError: new Error('gh failed') }).context,
+ ).toBe(context);
+ });
+
+ it('flags a failed confirmation read that keeps the PR locked', () => {
+ const result = resolvePullRequestActionLock({
+ ...live,
+ confirmError: new Error('device offline'),
+ confirmed: false,
+ });
+ expect(result.locked).toBe(true);
+ expect(result.refreshFailed).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.ts
new file mode 100644
index 00000000000..01eb95a189c
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveLinkedPullRequest } from '../useLinkedPullRequest';
+
+const pr = (number: number) => ({
+ number,
+ state: 'OPEN',
+ title: `PR ${number}`,
+ url: `u/${number}`,
+});
+
+const base = {
+ available: true,
+ branch: { branch: 'feat/x' },
+ branchConfirmed: true,
+ linkedPR: { pullRequest: pr(42), pullRequestStatus: 'ok' as const },
+ linkedPRConfirmed: true,
+};
+
+describe('resolveLinkedPullRequest', () => {
+ it('confirms a PR the live branch and lookup reads both answered', () => {
+ expect(resolveLinkedPullRequest(base)).toEqual({
+ confirmError: undefined,
+ confirmed: true,
+ pullRequest: pr(42),
+ });
+ });
+
+ // Regression: after an external checkout between sessions the persisted
+ // branch + linked PR painted the old PR, and its close / merge actions were
+ // live before the device answered.
+ it('paints but does not confirm a PR from persisted rows', () => {
+ expect(resolveLinkedPullRequest({ ...base, branchConfirmed: false })).toEqual({
+ confirmError: undefined,
+ confirmed: false,
+ pullRequest: pr(42),
+ });
+ expect(resolveLinkedPullRequest({ ...base, linkedPRConfirmed: false }).confirmed).toBe(false);
+ });
+
+ it('never confirms the topic snapshot stand-in', () => {
+ const result = resolveLinkedPullRequest({
+ ...base,
+ linkedPR: undefined,
+ linkedPRConfirmed: false,
+ snapshot: { branch: 'feat/x', github: { pullRequest: pr(7) } },
+ });
+ expect(result).toEqual({ confirmError: undefined, confirmed: false, pullRequest: pr(7) });
+ });
+
+ it('lets a confirmed empty lookup hide the snapshot PR', () => {
+ const result = resolveLinkedPullRequest({
+ ...base,
+ linkedPR: { pullRequest: null, pullRequestStatus: 'ok' },
+ snapshot: { branch: 'feat/x', github: { pullRequest: pr(7) } },
+ });
+ expect(result).toEqual({ confirmError: undefined, confirmed: false, pullRequest: null });
+ });
+
+ // Regression: a failed branch / linked-PR read left the persisted PR locked
+ // with no error and no retry in the PR pane.
+ it('reports the failed read that keeps the PR unconfirmed', () => {
+ const offline = new Error('device offline');
+ expect(
+ resolveLinkedPullRequest({ ...base, branchConfirmed: false, branchError: offline })
+ .confirmError,
+ ).toBe(offline);
+ expect(
+ resolveLinkedPullRequest({ ...base, linkedPRConfirmed: false, linkedPRError: offline })
+ .confirmError,
+ ).toBe(offline);
+ expect(
+ resolveLinkedPullRequest({ ...base, linkedPRError: offline }).confirmError,
+ ).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
index d27177d8ccc..fc8474bf447 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts
@@ -37,6 +37,50 @@ describe('usePullRequestActions', () => {
toastError.mockReset();
});
+ // Regression: the pane enabled close / merge / comment on a PR painted from
+ // persisted rows, so a click before the live reads settled could mutate a PR
+ // the branch had already moved off.
+ it('refuses every mutation while locked, and runs once unlocked', async () => {
+ runPullRequestAction.mockResolvedValue({ success: true });
+ pushGitBranch.mockResolvedValue({ success: true });
+ const mutateDetail = vi.fn().mockResolvedValue(undefined);
+ const { rerender, result } = renderHook(
+ ({ locked }) => usePullRequestActions({ ...params, locked, mutateDetail }),
+ { initialProps: { locked: true } },
+ );
+
+ await act(async () => {
+ expect(await result.current.run({ type: 'close' })).toBe(false);
+ expect(await result.current.push()).toBe(false);
+ });
+ expect(runPullRequestAction).not.toHaveBeenCalled();
+ expect(pushGitBranch).not.toHaveBeenCalled();
+ expect(result.current.busy).toBeUndefined();
+
+ rerender({ locked: false });
+ await act(async () => {
+ expect(await result.current.run({ type: 'close' })).toBe(true);
+ });
+ expect(runPullRequestAction).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets comments through but refuses policy actions while the merge context is stale', async () => {
+ runPullRequestAction.mockResolvedValue({ success: true });
+ const mutateDetail = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ usePullRequestActions({ ...params, mutateDetail, policyLocked: true }),
+ );
+
+ await act(async () => {
+ expect(
+ await result.current.run({ headRefOid: 'a'.repeat(40), method: 'squash', type: 'merge' }),
+ ).toBe(false);
+ expect(await result.current.run({ body: 'hi', type: 'comment' })).toBe(true);
+ });
+ expect(runPullRequestAction).toHaveBeenCalledTimes(1);
+ expect(runPullRequestAction.mock.calls[0][0].action.type).toBe('comment');
+ });
+
it('marks busy during the action and clears it afterwards', async () => {
const pending = deferred<{ success: boolean }>();
runPullRequestAction.mockReturnValue(pending.promise);
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/actionLock.ts b/src/features/Conversation/WorkingSidebar/PullRequest/actionLock.ts
new file mode 100644
index 00000000000..16ddca9d5e1
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/actionLock.ts
@@ -0,0 +1,53 @@
+import type { DeviceGitPullRequestMergeContext } from '@lobechat/types';
+
+interface ActionLockInput {
+ /** The sidebar's branch + linked-PR reads confirmed this PR number. */
+ confirmed: boolean;
+ /** The failed branch / linked-PR read that keeps `confirmed` false. */
+ confirmError?: unknown;
+ context: DeviceGitPullRequestMergeContext | null | undefined;
+ contextConfirmed: boolean;
+ contextError: unknown;
+ detailConfirmed: boolean;
+ detailError: unknown;
+}
+
+/**
+ * What the PR pane may act on. Persisted rows keep painting; mutations wait:
+ *
+ * - `locked`: the PR itself (branch, linked PR, detail) is not confirmed yet —
+ * every action, comments included, is refused.
+ * - `policyLocked`: the merge context (permissions, required checks, base
+ * drift) on screen is last session's — policy-driven actions (merge, update,
+ * bypass, close / reopen, change base) wait for the live read.
+ *
+ * A failed context read drops the cached policy rather than locking forever:
+ * the pane falls back to the core detail, as it does with no context at all,
+ * and the merge dock stops reporting it as loading.
+ *
+ * `refreshFailed`: a live read failed while the pane still paints a persisted
+ * row it cannot act on — the pane must say so and offer a retry.
+ */
+export const resolvePullRequestActionLock = ({
+ confirmError,
+ confirmed,
+ context,
+ contextConfirmed,
+ contextError,
+ detailConfirmed,
+ detailError,
+}: ActionLockInput) => {
+ const usableContext = contextConfirmed || !contextError ? context : undefined;
+ const locked = !confirmed || !detailConfirmed;
+ const policyLocked = usableContext !== undefined && !contextConfirmed;
+ return {
+ context: usableContext,
+ contextLoading: locked || policyLocked || (usableContext === undefined && !contextError),
+ locked,
+ policyLocked,
+ refreshFailed:
+ (!confirmed && !!confirmError) ||
+ (!detailConfirmed && !!detailError) ||
+ (!contextConfirmed && !!contextError),
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
index 9f56c6dc625..ec2188cd33c 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
@@ -14,6 +14,7 @@ import {
import { OverviewRow } from '../Overview/OverviewRow';
import { sectionStyles } from '../Overview/sectionStyles';
+import { resolvePullRequestActionLock } from './actionLock';
import Header from './Header';
import MergeDock from './MergeDock';
import Sections from './Sections';
@@ -40,21 +41,42 @@ const styles = createStaticStyles(({ css }) => ({
interface PullRequestProps {
active: boolean;
+ /**
+ * This session's branch and linked-PR reads confirmed `number`. Until then
+ * the pane may paint persisted rows, but must not mutate the PR.
+ */
+ confirmed: boolean;
+ /** The failed branch / linked-PR read keeping `confirmed` false. */
+ confirmError?: unknown;
deviceId?: string;
number: number;
onOpenTab: (tab: string) => void;
+ /** Re-run the branch / linked-PR reads that confirm `number`. */
+ onRetryConfirm?: () => void;
summary?: DeviceGitLinkedPullRequest;
url?: string;
workingDirectory: string;
}
const PullRequest = memo<PullRequestProps>(
- ({ active, deviceId, number, onOpenTab, summary, url, workingDirectory }) => {
+ ({
+ active,
+ confirmError,
+ confirmed,
+ deviceId,
+ number,
+ onOpenTab,
+ onRetryConfirm,
+ summary,
+ url,
+ workingDirectory,
+ }) => {
const { t } = useTranslation('chat');
const { t: tCommon } = useTranslation('common');
const {
data,
error: fetchError,
+ isConfirmed: detailConfirmed,
isLoading,
mutate,
} = useFetchGitPullRequestDetail(deviceId, workingDirectory, number, { active });
@@ -64,14 +86,33 @@ const PullRequest = memo<PullRequestProps>(
data?.detail?.number,
active && data?.detail?.state === 'open',
);
- const { data: context } = useFetchGitPullRequestMergeContext(
- deviceId,
- workingDirectory,
- data?.detail ?? undefined,
- );
+ const {
+ data: cachedContext,
+ error: contextError,
+ isConfirmed: contextConfirmed,
+ mutate: mutateContext,
+ } = useFetchGitPullRequestMergeContext(deviceId, workingDirectory, data?.detail ?? undefined);
const { data: aheadBehind } = useFetchGitAheadBehind(deviceId, workingDirectory);
+ // Stale content stays paintable; actions wait for the live reads.
+ const {
+ context,
+ contextLoading,
+ locked: actionsLocked,
+ policyLocked,
+ refreshFailed,
+ } = resolvePullRequestActionLock({
+ confirmError,
+ confirmed,
+ context: cachedContext,
+ contextConfirmed,
+ contextError,
+ detailConfirmed,
+ detailError: fetchError,
+ });
const actions = usePullRequestActions({
deviceId,
+ locked: actionsLocked,
+ policyLocked,
mutateDetail: mutate,
number,
workingDirectory,
@@ -90,6 +131,22 @@ const PullRequest = memo<PullRequestProps>(
};
}, [data?.detail, context, activity.data]);
const externalUrl = detail?.url ?? url;
+ const loadError = (error: unknown, onRetry: () => void) => (
+ <Flexbox className={sectionStyles.section}>
+ <OverviewRow
+ danger
+ icon={TriangleAlertIcon}
+ iconColor={cssVar.colorError}
+ title={error instanceof Error ? error.message : undefined}
+ value={t('workingPanel.pr.error.load')}
+ trailing={
+ <Button icon={<Icon icon={RefreshCwIcon} size={12} />} size={'small'} onClick={onRetry}>
+ {tCommon('retry')}
+ </Button>
+ }
+ />
+ </Flexbox>
+ );
if (isLoading && !data) return <PullRequestSkeleton summary={summary} />;
@@ -119,27 +176,7 @@ const PullRequest = memo<PullRequestProps>(
/>
);
- if (!detail)
- return (
- <Flexbox className={sectionStyles.section}>
- <OverviewRow
- danger
- icon={TriangleAlertIcon}
- iconColor={cssVar.colorError}
- title={fetchError instanceof Error ? fetchError.message : undefined}
- value={t('workingPanel.pr.error.load')}
- trailing={
- <Button
- icon={<Icon icon={RefreshCwIcon} size={12} />}
- size={'small'}
- onClick={() => void mutate()}
- >
- {tCommon('retry')}
- </Button>
- }
- />
- </Flexbox>
- );
+ if (!detail) return loadError(fetchError, () => void mutate());
const local = aheadBehind?.hasUpstream ? { ahead: aheadBehind.ahead } : undefined;
@@ -152,7 +189,15 @@ const PullRequest = memo<PullRequestProps>(
contentProps={{ className: styles.scrollContent }}
viewportProps={{ className: styles.viewport, style: { overflowX: 'hidden' } }}
>
+ {/* The persisted PR still paints, but stays locked until a live read lands. */}
+ {refreshFailed &&
+ loadError(confirmError ?? fetchError ?? contextError, () => {
+ onRetryConfirm?.();
+ void mutate();
+ void mutateContext();
+ })}
<Header
+ actionsDisabled={actionsLocked || policyLocked}
activityLoaded={!!activity.data}
detail={detail}
deviceId={deviceId}
@@ -160,6 +205,7 @@ const PullRequest = memo<PullRequestProps>(
onAction={actions.run}
/>
<Sections
+ actionsDisabled={actionsLocked}
activity={activity}
busy={actions.busy}
detail={detail}
@@ -169,7 +215,7 @@ const PullRequest = memo<PullRequestProps>(
</ScrollArea>
<MergeDock
busy={actions.busy}
- contextLoading={context === undefined}
+ contextLoading={contextLoading}
detail={detail}
error={actions.error}
local={local}
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.ts
new file mode 100644
index 00000000000..7da8c08d548
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.ts
@@ -0,0 +1,114 @@
+import type { DeviceGitLinkedPullRequest, WorkingDirGithubState } from '@lobechat/types';
+
+import { type GitLinkedPRSummary } from '@/services/git';
+import { useFetchGitBranch, useFetchGitLinkedPR } from '@/store/device';
+
+/** The git context the topic recorded for the working directory. */
+export interface PullRequestSnapshot {
+ branch?: string;
+ github?: WorkingDirGithubState;
+}
+
+interface ResolveLinkedPullRequestInput {
+ /** The working directory is readable here (local machine or a bound device). */
+ available: boolean;
+ branch?: { branch?: string; detached?: boolean };
+ branchConfirmed: boolean;
+ branchError?: unknown;
+ linkedPR?: GitLinkedPRSummary;
+ linkedPRConfirmed: boolean;
+ linkedPRError?: unknown;
+ snapshot?: PullRequestSnapshot;
+}
+
+/**
+ * The PR the sidebar shows for the working directory, and whether it may be
+ * acted on. Persisted rows and the topic snapshot are enough to paint the tab;
+ * only a PR that this session's branch read and linked-PR lookup both
+ * confirmed may be mutated — a stale row could otherwise close or merge a PR
+ * the repository has since moved off.
+ *
+ * `confirmError`: the failed read that keeps an unconfirmed PR locked, so the
+ * pane can say why and retry it.
+ */
+export const resolveLinkedPullRequest = ({
+ available,
+ branch,
+ branchConfirmed,
+ branchError,
+ linkedPR,
+ linkedPRConfirmed,
+ linkedPRError,
+ snapshot,
+}: ResolveLinkedPullRequestInput): {
+ confirmError: unknown;
+ confirmed: boolean;
+ pullRequest: DeviceGitLinkedPullRequest | null | undefined;
+} => {
+ const snapshotPR =
+ !branch || (snapshot?.branch === branch.branch && !branch.detached)
+ ? snapshot?.github?.pullRequest
+ : undefined;
+ // A settled empty lookup supersedes the snapshot; failures may keep displaying it.
+ const pullRequest = available
+ ? linkedPR?.pullRequestStatus === 'ok'
+ ? linkedPR.pullRequest
+ : (linkedPR?.pullRequest ?? snapshotPR)
+ : undefined;
+ const confirmed =
+ !!pullRequest &&
+ branchConfirmed &&
+ linkedPRConfirmed &&
+ linkedPR?.pullRequest?.number === pullRequest.number;
+ const confirmError = confirmed
+ ? undefined
+ : (!branchConfirmed && branchError) || (!linkedPRConfirmed && linkedPRError) || undefined;
+ return { confirmError, confirmed, pullRequest };
+};
+
+/** Branch → linked PR for the Working Sidebar's PR tab. */
+export const useLinkedPullRequest = ({
+ available,
+ deviceId,
+ gitPath,
+ isGithub,
+ snapshot,
+}: {
+ available: boolean;
+ deviceId?: string;
+ /** Set only for a readable GitHub working directory. */
+ gitPath?: string;
+ isGithub: boolean;
+ snapshot?: PullRequestSnapshot;
+}) => {
+ const {
+ data: branch,
+ error: branchError,
+ isConfirmed: branchConfirmed,
+ mutate: refreshBranch,
+ } = useFetchGitBranch(deviceId, gitPath);
+ const {
+ data: linkedPR,
+ error: linkedPRError,
+ isConfirmed: linkedPRConfirmed,
+ mutate: refresh,
+ } = useFetchGitLinkedPR(deviceId, gitPath, branch?.branch, isGithub);
+ return {
+ ...resolveLinkedPullRequest({
+ available,
+ branch,
+ branchConfirmed,
+ branchError,
+ linkedPR,
+ linkedPRConfirmed,
+ linkedPRError,
+ snapshot,
+ }),
+ /** Re-run the reads that confirm the PR (branch, then its linked PR). */
+ onRetryConfirm: () => {
+ void refreshBranch();
+ void refresh();
+ },
+ refresh,
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
index d8b42f50669..6ef3c2bb881 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts
@@ -19,14 +19,26 @@ const DOCK_KINDS = new Set<PullRequestBusy>([
interface UsePullRequestActionsParams {
deviceId?: string;
+ /**
+ * The PR is only known from persisted rows so far: refuse every mutation so
+ * a click on stale content cannot act on a PR the branch has moved off.
+ */
+ locked?: boolean;
mutateDetail: () => Promise<unknown>;
number: number;
+ /**
+ * The merge context (permissions, required checks) is still last session's:
+ * refuse policy-driven mutations, but let comments through.
+ */
+ policyLocked?: boolean;
workingDirectory: string;
}
export const usePullRequestActions = ({
deviceId,
+ locked = false,
mutateDetail,
+ policyLocked = false,
number,
workingDirectory,
}: UsePullRequestActionsParams) => {
@@ -34,10 +46,15 @@ export const usePullRequestActions = ({
const [error, setError] = useState<string>();
const busyRef = useRef(false);
const retryRef = useRef<() => Promise<boolean>>(undefined);
+ const lockedRef = useRef(locked);
+ lockedRef.current = locked;
+ const policyLockedRef = useRef(policyLocked);
+ policyLockedRef.current = policyLocked;
const perform = useCallback(
async (kind: PullRequestBusy, request: () => Promise<DeviceGitPullRequestActionResult>) => {
- if (busyRef.current) return false;
+ if (busyRef.current || lockedRef.current) return false;
+ if (policyLockedRef.current && kind !== 'comment') return false;
busyRef.current = true;
setBusy(kind);
const isDockAction = DOCK_KINDS.has(kind);
diff --git a/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx b/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx
index 24ce4b4581f..e898b09854e 100644
--- a/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx
+++ b/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx
@@ -10,6 +10,7 @@ import {
cssVar as themeCssVar,
Flexbox,
PatchDiff,
+ Skeleton,
toast,
} from '@lobehub/ui';
import { CopyIcon, LocateFixedIcon, Undo2Icon } from 'lucide-react';
@@ -68,6 +69,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
deletions: css`
color: ${cssVar.colorError};
`,
+ pending: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ `,
empty: css`
padding-block: 12px;
color: ${cssVar.colorTextTertiary};
@@ -190,13 +195,16 @@ interface FileItemHeaderProps {
onReverted?: () => void;
/** When provided, enables the per-file revert button (unstaged mode only). */
revertContext?: { deviceId?: string; workingDirectory: string };
+ /** Keep the revert button visible but inert, e.g. while the row is a
+ * persisted summary the live read has not confirmed yet. */
+ revertDisabled?: boolean;
// Status reserved for future use (e.g. dim deleted entries) — keep on the
// shape so the parent doesn't need to re-derive it later.
status: GitFileDiffStatus;
}
export const FileItemHeader = memo<FileItemHeaderProps>(
- ({ filePath, additions, deletions, hideDir, revertContext, onReverted }) => {
+ ({ filePath, additions, deletions, hideDir, revertContext, revertDisabled, onReverted }) => {
const { t } = useTranslation('chat');
const revealInFilesTab = useGlobalStore((s) => s.revealInFilesTab);
@@ -225,7 +233,7 @@ export const FileItemHeader = memo<FileItemHeaderProps>(
const handleRevert = useCallback(
(event: MouseEvent<HTMLDivElement>) => {
event.stopPropagation();
- if (!revertContext) return;
+ if (!revertContext || revertDisabled) return;
confirmModal({
cancelText: t('workingPanel.review.revert.confirm.cancel'),
content: t('workingPanel.review.revert.confirm.description'),
@@ -259,7 +267,7 @@ export const FileItemHeader = memo<FileItemHeaderProps>(
title: t('workingPanel.review.revert.confirm.title'),
});
},
- [fileName, filePath, onReverted, revertContext, t],
+ [fileName, filePath, onReverted, revertContext, revertDisabled, t],
);
return (
@@ -298,6 +306,8 @@ export const FileItemHeader = memo<FileItemHeaderProps>(
{revertContext && (
<ActionIcon
className={`${styles.rowAction} ${styles.revertDanger}`}
+ data-testid="revert-file"
+ disabled={revertDisabled}
icon={Undo2Icon}
size={'small'}
title={t('workingPanel.review.revert')}
@@ -319,6 +329,8 @@ interface FileItemBodyProps {
filePath: string;
isBinary: boolean;
patch: string;
+ /** Diff text not loaded yet — show a placeholder instead of the error line. */
+ pending?: boolean;
/** Inline word-level diff highlighting; off → plain line-level. */
textDiff: boolean;
truncated: boolean;
@@ -332,6 +344,7 @@ const FileItemBody = memo<FileItemBodyProps>(
composerTarget,
filePath,
patch,
+ pending,
isBinary,
truncated,
expanded,
@@ -394,6 +407,12 @@ const FileItemBody = memo<FileItemBodyProps>(
if (isBinary) return <div className={styles.empty}>{t('workingPanel.review.binary')}</div>;
if (truncated) return <div className={styles.empty}>{t('workingPanel.review.tooLarge')}</div>;
+ if (!patch && pending)
+ return (
+ <div aria-busy className={styles.pending} data-testid={'review-diff-pending'}>
+ <Skeleton.Text rows={3} width={['80%', '60%', '70%']} />
+ </div>
+ );
if (!patch) return <div className={styles.empty}>{t('workingPanel.review.error')}</div>;
return (
diff --git a/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx b/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx
index c8941519512..651366262ef 100644
--- a/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx
+++ b/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx
@@ -73,10 +73,15 @@ interface FileRowProps {
mode: ReviewMode;
onReverted: () => void;
onToggle: () => void;
+ /** The diff text is still loading (row comes from the persisted summary). */
+ pending?: boolean;
/** Absolute path of the owning repo — used as the working directory for
* revert operations so submodule files revert inside the submodule, not
* the parent repo. */
repoAbsolutePath: string;
+ /** The row comes from the persisted summary, not the live read: revert stays
+ * disabled until the device confirms what the path holds now. */
+ stale?: boolean;
textDiff: boolean;
viewMode: 'unified' | 'split';
wordWrap: boolean;
@@ -94,7 +99,9 @@ const FileRow = memo<FileRowProps>(
mode,
onReverted,
onToggle,
+ pending,
repoAbsolutePath,
+ stale,
textDiff,
viewMode,
wordWrap,
@@ -130,6 +137,7 @@ const FileRow = memo<FileRowProps>(
deletions={entry.deletions}
filePath={entry.filePath}
hideDir={hideDir}
+ revertDisabled={stale}
status={entry.status}
revertContext={
mode === 'unstaged' ? { deviceId, workingDirectory: repoAbsolutePath } : undefined
@@ -156,6 +164,7 @@ const FileRow = memo<FileRowProps>(
filePath={entry.filePath}
isBinary={entry.isBinary}
patch={entry.patch}
+ pending={pending}
textDiff={textDiff}
truncated={entry.truncated}
viewMode={viewMode}
diff --git a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
index 3df06e6b3f9..2b3ec4667c1 100644
--- a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
@@ -1,7 +1,8 @@
+import { confirmModal } from '@lobehub/ui';
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import { FileItemHeader } from '../FileItem';
+import FileItemBody, { FileItemHeader } from '../FileItem';
const mockRevealInFilesTab = vi.fn();
@@ -16,9 +17,18 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({
<button type="button" {...props} onClick={onClick} />
),
confirmModal: vi.fn(),
+ Skeleton: { Text: () => <div data-testid="skeleton-text" /> },
toast: { error: vi.fn(), success: vi.fn() },
}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (s: any) => any) => selector({ addChatContextSelection: vi.fn() }),
+}));
+
vi.mock('@/services/git', () => ({
gitService: { revertGitFile: vi.fn() },
}));
@@ -55,3 +65,76 @@ describe('FileItemHeader — reveal in tree', () => {
expect(parentSpy).not.toHaveBeenCalled();
});
});
+
+describe('FileItemHeader — revert', () => {
+ const revertContext = { deviceId: 'device-1', workingDirectory: '/repo' };
+
+ it('asks for confirmation before reverting a live row', () => {
+ vi.mocked(confirmModal).mockClear();
+ render(
+ <FileItemHeader
+ additions={1}
+ deletions={0}
+ filePath="src/foo.ts"
+ revertContext={revertContext}
+ status="modified"
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId('revert-file'));
+
+ expect(confirmModal).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: a row painted from the persisted summary kept revert enabled,
+ // so it could discard content at that path the summary never showed.
+ it('keeps revert inert while the row is an unconfirmed summary', () => {
+ vi.mocked(confirmModal).mockClear();
+ render(
+ <FileItemHeader
+ revertDisabled
+ additions={1}
+ deletions={0}
+ filePath="src/foo.ts"
+ revertContext={revertContext}
+ status="modified"
+ />,
+ );
+
+ const button = screen.getByTestId('revert-file');
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+
+ expect(confirmModal).not.toHaveBeenCalled();
+ });
+});
+
+describe('FileItemBody — summary rows', () => {
+ const props = {
+ composerTarget: { contextKey: 'ctx', writable: true } as any,
+ expanded: true,
+ filePath: 'src/foo.ts',
+ isBinary: false,
+ patch: '',
+ textDiff: true,
+ truncated: false,
+ viewMode: 'unified' as const,
+ wordWrap: false,
+ workingDirectory: '/repo',
+ };
+
+ // Regression: a row painted from the persisted summary has no diff text yet;
+ // without the pending state it read as a load error until the live diff landed.
+ it('shows a placeholder, not the error line, while the diff text is pending', () => {
+ render(<FileItemBody {...props} pending />);
+
+ expect(screen.getByTestId('review-diff-pending')).toBeInTheDocument();
+ expect(screen.queryByText('workingPanel.review.error')).not.toBeInTheDocument();
+ });
+
+ it('still reports a missing diff once the live read settled', () => {
+ render(<FileItemBody {...props} />);
+
+ expect(screen.getByText('workingPanel.review.error')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Review/index.tsx b/src/features/Conversation/WorkingSidebar/Review/index.tsx
index ca7b20c2f63..724be41c1b3 100644
--- a/src/features/Conversation/WorkingSidebar/Review/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Review/index.tsx
@@ -32,6 +32,7 @@ import FileTreeNav from './FileTreeNav';
import GroupHeader from './GroupHeader';
import { getDefaultExpandedKeys, itemKey } from './reviewTreeNodes';
import {
+ getReviewSummaryState,
invalidateGitReviewCaches,
type ReviewMode,
useGitRemoteBranches,
@@ -241,13 +242,16 @@ const Review = memo<ReviewProps>(
});
};
- const { data, isLoading, isValidating } = useReviewPatches(
+ // Stale-first: after a reload the replica paints the last persisted summary
+ // (paths + counts, no diff text); expanded rows wait for the live diff.
+ const { data, error, isLoading, isValidating } = useReviewPatches(
workingDirectory,
mode,
baseOverride,
deviceId,
active,
);
+ const { diffPending, isSummary } = getReviewSummaryState(data, error);
const invalidateReviewData = useCallback(
async () =>
invalidateGitReviewCaches({
@@ -658,7 +662,9 @@ const Review = memo<ReviewProps>(
expanded={expanded}
key={key}
mode={mode}
+ pending={diffPending}
repoAbsolutePath={group.absolutePath}
+ stale={isSummary}
textDiff={textDiff}
viewMode={viewMode}
wordWrap={wordWrap}
diff --git a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
index 13c91f79b73..119e3f72724 100644
--- a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts
@@ -1,4 +1,10 @@
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
+
+import { mutate } from '@/libs/swr';
+import { gitService } from '@/services/git';
import {
getReviewRefreshInterval,
@@ -15,9 +21,9 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
},
}));
-vi.mock('@/libs/swr', () => ({
+vi.mock('@/libs/swr', async (importOriginal) => ({
+ ...(await importOriginal()),
mutate: vi.fn(),
- useClientDataSWR: vi.fn(() => ({ data: undefined })),
}));
const revalidateGitStatus = vi.hoisted(() => vi.fn());
@@ -34,53 +40,55 @@ vi.mock('@/services/git', () => ({
},
}));
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
describe('useReviewPatches', () => {
beforeEach(() => {
vi.clearAllMocks();
platform.isDesktop = true;
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({ patches: [] } as any);
+ vi.mocked(gitService.getGitBranchDiff).mockResolvedValue({ patches: [] } as any);
});
it('polls while the review tab is active and disables polling while hidden', () => {
expect(getReviewRefreshInterval('unstaged', true)).toBe(10_000);
expect(getReviewRefreshInterval('branch', true)).toBe(30_000);
expect(getReviewRefreshInterval('unstaged', false)).toBe(0);
+ });
- useReviewPatches('/repo', 'unstaged', undefined, undefined, true);
-
- expect(useClientDataSWR).toHaveBeenCalledWith(
- ['device:gitReviewPatches', 'local', '/repo', 'unstaged', ''],
- expect.any(Function),
- expect.objectContaining({
- refreshInterval: 10_000,
- refreshWhenHidden: false,
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
- }),
+ it('reads the working tree only while the review tab is active', async () => {
+ const hidden = renderHook(
+ () => useReviewPatches('/repo', 'branch', 'origin/canary', 'device-1', false),
+ { wrapper },
);
+ expect(hidden.result.current.data).toBeUndefined();
+ expect(hidden.result.current.isLoading).toBe(false);
+ hidden.unmount();
+ expect(gitService.getGitBranchDiff).not.toHaveBeenCalled();
- vi.clearAllMocks();
-
- useReviewPatches('/repo', 'branch', 'origin/canary', 'device-1', false);
-
- expect(useClientDataSWR).toHaveBeenCalledWith(
- null,
- expect.any(Function),
- expect.objectContaining({
- refreshInterval: 0,
+ renderHook(() => useReviewPatches('/repo', 'unstaged', undefined, undefined, true), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(gitService.getGitWorkingTreePatches).toHaveBeenCalledWith({
+ deviceId: undefined,
+ path: '/repo',
}),
);
});
- it('does not request local git patches from a web client without a target device', () => {
+ it('does not request local git patches from a web client without a target device', async () => {
platform.isDesktop = false;
- useReviewPatches('/repo', 'unstaged', undefined, undefined, true);
-
- expect(useClientDataSWR).toHaveBeenCalledWith(
- null,
- expect.any(Function),
- expect.objectContaining({ refreshInterval: 10_000 }),
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, undefined, true),
+ { wrapper },
);
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(result.current.data).toBeUndefined();
+ expect(gitService.getGitWorkingTreePatches).not.toHaveBeenCalled();
});
it('invalidates review patches and related git tree status caches together', async () => {
diff --git a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
index 498bf098393..9b5d9f641d6 100644
--- a/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
+++ b/src/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
@@ -1,6 +1,7 @@
export {
getGitReviewPatchesKey,
getReviewRefreshInterval,
+ getReviewSummaryState,
invalidateGitReviewCaches,
type ReviewMode,
type ReviewPatchesData,
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 98c8e8b5618..48fdc598adf 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -75,12 +75,7 @@ import { useChatStore } from '@/store/chat';
import { chatPortalSelectors, portalThreadSelectors, topicSelectors } from '@/store/chat/selectors';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import {
- deviceSelectors,
- useDeviceStore,
- useFetchGitBranch,
- useFetchGitLinkedPR,
-} from '@/store/device';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -94,6 +89,7 @@ import Overview from './Overview';
import { getStatusDeviceId } from './Overview/overviewData';
import OverviewSlot from './OverviewSlot';
import PullRequest from './PullRequest';
+import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
import WorkspaceTab from './WorkspaceTab';
@@ -443,24 +439,17 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const isGithub =
repoType === 'github' || (!repoType && !!snapshotConfig?.git?.github?.pullRequest);
const gitPath = filesystemEnvironmentAvailable && isGithub ? workingDirectory : undefined;
- const { data: branchData } = useFetchGitBranch(remoteDeviceId, gitPath);
- const { data: linkedPR, mutate: refreshPullRequest } = useFetchGitLinkedPR(
- remoteDeviceId,
+ const {
+ pullRequest,
+ refresh: refreshPullRequest,
+ ...pullRequestLink // confirmed, confirmError, onRetryConfirm
+ } = useLinkedPullRequest({
+ available: filesystemEnvironmentAvailable && !!workingDirectory,
+ deviceId: remoteDeviceId,
gitPath,
- branchData?.branch,
isGithub,
- );
- const snapshotPR =
- !branchData || (snapshotConfig?.git?.branch === branchData.branch && !branchData.detached)
- ? snapshotConfig?.git?.github?.pullRequest
- : undefined;
- // A settled empty lookup supersedes the snapshot; failures may keep displaying it.
- const pullRequest =
- filesystemEnvironmentAvailable && workingDirectory
- ? linkedPR?.pullRequestStatus === 'ok'
- ? linkedPR.pullRequest
- : (linkedPR?.pullRequest ?? snapshotPR)
- : undefined;
+ snapshot: snapshotConfig?.git,
+ });
const paramsAvailable = !isHetero;
// The in-app browser pages are renderer-retained Electron webviews — desktop only.
const browserAvailable = isDesktop;
@@ -1172,6 +1161,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
<Flexbox className={styles.pane}>
<PullRequest
active={!!showRightPanel && activeTab === 'pr'}
+ {...pullRequestLink}
deviceId={remoteDeviceId}
key={JSON.stringify([remoteDeviceId, workingDirectory, pullRequest.number])}
number={pullRequest.number}
diff --git a/src/store/device/gitHooks.test.ts b/src/store/device/gitHooks.test.ts
index b213f581bfd..d6dbf0440f3 100644
--- a/src/store/device/gitHooks.test.ts
+++ b/src/store/device/gitHooks.test.ts
@@ -90,7 +90,8 @@ describe('pullRequestDetailRefreshInterval', () => {
});
});
-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', async (importOriginal) => ({
+ ...(await importOriginal()),
useActiveWorkspaceId: () => 'test-workspace',
}));
afterEach(() => vi.restoreAllMocks());
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 15c1baefa25..03b14766819 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -1,8 +1,4 @@
import { isDesktop } from '@lobechat/const';
-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 {
@@ -20,6 +16,18 @@ import { mutate, useClientDataSWR } from '@/libs/swr';
import { deviceKeys, localFileKeys } from '@/libs/swr/keys';
import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/services/git';
+import {
+ gitLinkedPRKey,
+ gitPullRequestKey,
+ gitPullRequestMergeContextKey,
+ type GitPullRequestMergeContextParams,
+ type GitPullRequestParams,
+ gitReviewPatchesKey,
+ type GitReviewRead,
+ type ReviewMode,
+ type ReviewPatchesData,
+} from './gitReview/projection';
+import { type GitReviewStore, useGitReviewStore, warmPullRequestReplicas } from './gitReview/store';
import {
type GitDiffStats,
gitStatusKey,
@@ -28,24 +36,13 @@ import {
} from './gitStatus/projection';
import { type GitStatusStore, useGitStatusStore } from './gitStatus/store';
-export type ReviewMode = 'unstaged' | 'branch';
+export type { ReviewMode, ReviewPatchesData } from './gitReview/projection';
+export { getReviewSummaryState, toReviewPatchesSummary } from './gitReview/projection';
const UNSTAGED_REVIEW_REFRESH_INTERVAL = 10 * 1000;
const BRANCH_REVIEW_REFRESH_INTERVAL = 30 * 1000;
const PULL_REQUEST_DETAIL_REFRESH_INTERVAL = 30 * 1000;
-export interface ReviewPatchesData {
- baseRef?: string;
- headRef?: string;
- mode: ReviewMode;
- patches: GitWorkingTreePatch[];
- /**
- * Per-submodule patch groups. Undefined when the parent has no dirty
- * submodules (unstaged) or no submodule pointer differences (branch).
- */
- submodules?: SubmoduleWorkingTreePatches[];
-}
-
/**
* Git read hooks for a working directory, transport-agnostic: the fetcher goes
* through `gitService`, which dispatches Electron IPC (local) vs `device.*` RPC
@@ -56,29 +53,6 @@ export interface ReviewPatchesData {
const isEnabled = (deviceId: string | undefined, path: string | undefined): path is string =>
!!path && (!!deviceId || isDesktop);
-const fetchUnstagedReviewPatches = async (
- dirPath: string,
- deviceId: string | undefined,
-): Promise<ReviewPatchesData> => {
- const result = await gitService.getGitWorkingTreePatches({ deviceId, path: dirPath });
- return { mode: 'unstaged', patches: result?.patches ?? [], submodules: result?.submodules };
-};
-
-const fetchBranchReviewPatches = async (
- dirPath: string,
- baseRef: string | undefined,
- deviceId: string | undefined,
-): Promise<ReviewPatchesData> => {
- const result = await gitService.getGitBranchDiff({ baseRef, deviceId, path: dirPath });
- return {
- baseRef: result?.baseRef,
- headRef: result?.headRef,
- mode: 'branch',
- patches: result?.patches ?? [],
- submodules: result?.submodules,
- };
-};
-
export const getReviewRefreshInterval = (mode: ReviewMode, active: boolean) => {
if (!active) return 0;
return mode === 'branch' ? BRANCH_REVIEW_REFRESH_INTERVAL : UNSTAGED_REVIEW_REFRESH_INTERVAL;
@@ -109,6 +83,7 @@ export const invalidateGitReviewCaches = async ({
const cacheDeviceId = deviceId ?? 'local';
await Promise.all([
+ // The review replica syncs under this key, so this re-runs its read.
mutate(deviceKeys.gitReviewPatches(cacheDeviceId, dirPath, mode, baseRef ?? '')),
useGitStatusStore
.getState()
@@ -117,31 +92,127 @@ export const invalidateGitReviewCaches = async ({
]);
};
+export interface GitReplicaReadResult<T> {
+ data: T | undefined;
+ error: unknown;
+ /**
+ * The device answered this session. A row hydrated from storage paints, but
+ * is not proof enough to act on (e.g. mutate the PR it names).
+ */
+ isConfirmed: boolean;
+ /** Nothing to paint yet (no persisted row, no response) and a read is pending. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /** Re-run the read (SWR-shaped, for the existing refresh callers). */
+ mutate: () => Promise<unknown>;
+}
+
+type GitReplicaSyncOptions<TStored> = ReplicaSyncSchedule & {
+ onHydrated?: (data: TStored) => void;
+ onSuccess?: (data: TStored) => void;
+};
+
+interface ReplicaReadSlice<TParams, TStored> {
+ useSync: (
+ params: TParams | null | undefined,
+ options?: GitReplicaSyncOptions<TStored> & { shouldRetryOnError?: boolean },
+ ) => {
+ error: unknown;
+ isHydrated: boolean;
+ isValidating: boolean;
+ revalidate: () => Promise<unknown>;
+ };
+}
+
+/**
+ * Read one of the Review / PR replicas (see `./gitReview`): the persisted row
+ * paints first, the device read confirms it in the background. Returns the
+ * SWR-like shape the Review / PR tabs were written against.
+ */
+type ReplicaEntriesSelector = (
+ state: GitReviewStore,
+) => Record<string, { source?: string } | undefined>;
+
+const useGitReviewReplica = <TParams, TStored>(
+ pick: (slices: GitReviewStore['slices']) => ReplicaReadSlice<TParams, TStored>,
+ selectMap: (state: GitReviewStore) => Record<string, TStored>,
+ selectEntries: ReplicaEntriesSelector,
+ toKey: (params: TParams) => string,
+ params: TParams | null,
+ schedule: GitReplicaSyncOptions<TStored>,
+) => {
+ const key = params ? toKey(params) : undefined;
+ const stored = useGitReviewStore((s) => (key ? selectMap(s)[key] : undefined));
+ // Only a head response makes the row authoritative (`source: 'server'`).
+ const isConfirmed = useGitReviewStore((s) => !!key && selectEntries(s)[key]?.source === 'server');
+ // The driver forwards SWR options as given: a failed git read (dead path,
+ // unreachable device, missing `gh`) is not retried, like the SWR hooks these replaced.
+ const { error, isHydrated, isValidating, revalidate } = pick(
+ useGitReviewStore.getState().slices,
+ ).useSync(params, { ...schedule, shouldRetryOnError: false });
+
+ return {
+ error,
+ isConfirmed,
+ isLoading: !!params && stored === undefined && !error && (!isHydrated || isValidating),
+ isValidating,
+ mutate: revalidate,
+ stored,
+ };
+};
+
+/** A `GitReviewRead` replica, unwrapped into the SWR-shaped result. */
+const useGitReviewRead = <TParams, T>(
+ pick: (slices: GitReviewStore['slices']) => ReplicaReadSlice<TParams, GitReviewRead<T>>,
+ selectMap: (state: GitReviewStore) => Record<string, GitReviewRead<T>>,
+ selectEntries: ReplicaEntriesSelector,
+ toKey: (params: TParams) => string,
+ params: TParams | null,
+ schedule: GitReplicaSyncOptions<GitReviewRead<T>>,
+): GitReplicaReadResult<T> => {
+ const { stored, ...rest } = useGitReviewReplica(
+ pick,
+ selectMap,
+ selectEntries,
+ toKey,
+ params,
+ schedule,
+ );
+ return { ...rest, data: stored?.value };
+};
+
+/**
+ * Review tab diff. A replica: after a reload the persisted summary (paths +
+ * line counts, `summaryOnly`, no diff text) paints first, and the live read
+ * replaces it with the full diff.
+ */
export const useReviewPatches = (
dirPath: string | undefined,
mode: ReviewMode,
baseRef?: string,
deviceId?: string,
active = true,
-) => {
+): GitReplicaReadResult<ReviewPatchesData> => {
const enabled = active && isEnabled(deviceId, dirPath);
- const key = enabled ? getGitReviewPatchesKey({ baseRef, deviceId, dirPath, mode }) : null;
-
- return useClientDataSWR<ReviewPatchesData>(
- key,
- () =>
- mode === 'branch'
- ? fetchBranchReviewPatches(dirPath!, baseRef, deviceId)
- : fetchUnstagedReviewPatches(dirPath!, deviceId),
+ const params = useMemo(
+ () => (enabled ? { baseRef, deviceId, mode, path: dirPath! } : null),
+ [enabled, baseRef, deviceId, mode, dirPath],
+ );
+ const { stored, ...rest } = useGitReviewReplica(
+ (slices) => slices.reviewPatches,
+ (s) => s.gitReviewPatchesMap,
+ (s) => s.gitReviewPatchesReplica.entries,
+ gitReviewPatchesKey,
+ params,
{
focusThrottleInterval: mode === 'branch' ? 30 * 1000 : 5 * 1000,
refreshInterval: getReviewRefreshInterval(mode, active),
refreshWhenHidden: false,
revalidateOnFocus: true,
revalidateOnReconnect: true,
- shouldRetryOnError: false,
},
);
+ return { ...rest, data: stored };
};
interface GitStatusReadResult<T> {
@@ -313,14 +384,36 @@ export const useFetchGitLinkedPR = (
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 },
+) => {
+ const enabled = isGithub && !!branch && isEnabled(deviceId, path);
+ const params = useMemo(
+ () => (enabled ? { branch: branch!, deviceId, path: path! } : null),
+ [enabled, branch, deviceId, path],
+ );
+ // The PR tab mounts the moment the linked PR is known; start reading its
+ // persisted detail / activity then, so the tab body paints from storage on
+ // its first frame instead of a skeleton while its own hydration reads them.
+ const warm = useCallback(
+ (read: GitReviewRead<GitLinkedPRSummary>) => {
+ const number = read.value?.pullRequest?.number;
+ if (number !== undefined && path) warmPullRequestReplicas({ deviceId, number, path });
+ },
+ [deviceId, path],
);
+ return useGitReviewRead(
+ (slices) => slices.linkedPR,
+ (s) => s.gitLinkedPRMap,
+ (s) => s.gitLinkedPRReplica.entries,
+ gitLinkedPRKey,
+ params,
+ {
+ dedupingInterval: 60 * 1000,
+ focusThrottleInterval: 60 * 1000,
+ onHydrated: warm,
+ onSuccess: warm,
+ },
+ );
+};
/**
* Compact uncommitted-diff counts for the composer's `+N −M` chip. There is no
@@ -405,21 +498,27 @@ export const useFetchGitPullRequestDetail = (
path: string | undefined,
number: number | undefined,
{ active = true }: { active?: boolean } = {},
-) =>
- useClientDataSWR<DeviceGitPullRequestDetailResult | undefined>(
- number !== undefined && isEnabled(deviceId, path)
- ? deviceKeys.gitPullRequestDetail(deviceId ?? 'local', path, number)
- : null,
- () =>
- gitService.getPullRequestDetail({ coreOnly: true, deviceId, number: number!, path: path! }),
+) => {
+ const enabled = number !== undefined && isEnabled(deviceId, path);
+ const params = useMemo(
+ () => (enabled ? { deviceId, number: number!, path: path! } : null),
+ [enabled, deviceId, number, path],
+ );
+ return useGitReviewRead(
+ (slices) => slices.pullRequestDetail,
+ (s) => s.gitPullRequestDetailMap,
+ (s) => s.gitPullRequestDetailReplica.entries,
+ gitPullRequestKey,
+ params,
{
dedupingInterval: 30_000,
focusThrottleInterval: 60 * 1000,
- refreshInterval: (detail) => pullRequestDetailRefreshInterval(detail, active),
+ refreshInterval: (latest?: GitReviewRead<DeviceGitPullRequestDetailResult>) =>
+ pullRequestDetailRefreshInterval(latest?.value, active),
revalidateOnFocus: true,
- shouldRetryOnError: false,
},
);
+};
/** Activity starts once core data can paint; its failure never hides the PR. */
export const useFetchGitPullRequestActivity = (
@@ -427,19 +526,25 @@ export const useFetchGitPullRequestActivity = (
path: string | undefined,
number: number | undefined,
active = true,
-) =>
- useClientDataSWR<DeviceGitPullRequestActivity>(
- number !== undefined && isEnabled(deviceId, path)
- ? deviceKeys.gitPullRequestActivity(deviceId ?? 'local', path, number)
- : null,
- () => gitService.getPullRequestActivity({ deviceId, number: number!, path: path! }),
+) => {
+ const enabled = number !== undefined && isEnabled(deviceId, path);
+ const params = useMemo(
+ () => (enabled ? { deviceId, number: number!, path: path! } : null),
+ [enabled, deviceId, number, path],
+ );
+ return useGitReviewRead<GitPullRequestParams, DeviceGitPullRequestActivity>(
+ (slices) => slices.pullRequestActivity,
+ (s) => s.gitPullRequestActivityMap,
+ (s) => s.gitPullRequestActivityReplica.entries,
+ gitPullRequestKey,
+ params,
{
dedupingInterval: 30_000,
focusThrottleInterval: 60_000,
refreshInterval: active ? 30_000 : 0,
- shouldRetryOnError: false,
},
);
+};
/**
* Slow merge context (permission, branch protection, base drift), keyed on the
@@ -450,33 +555,37 @@ export const useFetchGitPullRequestMergeContext = (
path: string | undefined,
detail:
Pick<DeviceGitPullRequestDetail, 'baseRefName' | 'headRefOid' | 'number' | 'repo'> | undefined,
-) =>
- useClientDataSWR<DeviceGitPullRequestMergeContext | null | undefined>(
- detail && isEnabled(deviceId, path)
- ? deviceKeys.gitPullRequestMergeContext(
- deviceId ?? 'local',
- path,
- detail.number,
- detail.headRefOid,
- detail.baseRefName,
- )
- : null,
+) => {
+ const enabled = !!detail && isEnabled(deviceId, path);
+ const { baseRefName, headRefOid, number } = detail ?? {};
+ const repoName = detail?.repo.name;
+ const repoOwner = detail?.repo.owner;
+ const params = useMemo(
() =>
- gitService.getPullRequestMergeContext({
- baseRefName: detail!.baseRefName,
- deviceId,
- headRefOid: detail!.headRefOid,
- number: detail!.number,
- path: path!,
- repo: detail!.repo,
- }),
- {
- dedupingInterval: 30_000,
- focusThrottleInterval: 60 * 1000,
- revalidateOnFocus: true,
- shouldRetryOnError: false,
- },
+ enabled
+ ? {
+ baseRefName: baseRefName!,
+ deviceId,
+ headRefOid: headRefOid!,
+ number: number!,
+ path: path!,
+ repo: { name: repoName!, owner: repoOwner! },
+ }
+ : null,
+ [enabled, baseRefName, deviceId, headRefOid, number, path, repoName, repoOwner],
);
+ return useGitReviewRead<
+ GitPullRequestMergeContextParams,
+ DeviceGitPullRequestMergeContext | null
+ >(
+ (slices) => slices.pullRequestMergeContext,
+ (s) => s.gitPullRequestMergeContextMap,
+ (s) => s.gitPullRequestMergeContextReplica.entries,
+ gitPullRequestMergeContextKey,
+ params,
+ { dedupingInterval: 30_000, focusThrottleInterval: 60 * 1000, revalidateOnFocus: true },
+ );
+};
/**
* Lazy-loaded list of remote branches under `refs/remotes/origin/*`.
diff --git a/src/store/device/gitReview/projection.ts b/src/store/device/gitReview/projection.ts
new file mode 100644
index 00000000000..a887a38accd
--- /dev/null
+++ b/src/store/device/gitReview/projection.ts
@@ -0,0 +1,232 @@
+import type {
+ GitWorkingTreePatch,
+ SubmoduleWorkingTreePatches,
+} from '@lobechat/electron-client-ipc';
+import type {
+ DeviceGitPullRequestActivity,
+ DeviceGitPullRequestDetailResult,
+ DeviceGitPullRequestMergeContext,
+} from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+import { deviceKeys } from '@/libs/swr/keys';
+import type { GitLinkedPRSummary } from '@/services/git';
+
+/**
+ * The Working Sidebar Review and Pull Request tab reads. They are replicas so
+ * a reload paints the last file list / PR on the first frame and the device
+ * read only confirms it.
+ *
+ * Rows are partitioned by the cache scope (user + workspace) and keyed by
+ * device + directory (+ mode / base / branch / PR number), so two devices that
+ * share a path never paint each other's state. None of these payloads carry
+ * credentials. Each resource adopts the SWR key the app already revalidates
+ * by (`syncKey`), so `invalidateGitReviewCaches` and the PR actions' `mutate`
+ * calls keep refreshing them.
+ */
+
+export type ReviewMode = 'unstaged' | 'branch';
+
+export interface ReviewPatchesData {
+ baseRef?: string;
+ headRef?: string;
+ mode: ReviewMode;
+ patches: GitWorkingTreePatch[];
+ /**
+ * Per-submodule patch groups. Undefined when the parent has no dirty
+ * submodules (unstaged) or no submodule pointer differences (branch).
+ */
+ submodules?: SubmoduleWorkingTreePatches[];
+ /**
+ * Set on the persisted summary (see `toReviewPatchesSummary`): paths and
+ * line counts are real, but every `patch` body is empty until the live read
+ * lands.
+ */
+ summaryOnly?: boolean;
+}
+
+/** `local` stands for this machine, like the SWR device keys. */
+const LOCAL = 'local';
+const joinKey = (...parts: (string | number)[]) => parts.join('\u0000');
+
+/**
+ * One answered read. The value is wrapped so a read that answered with nothing
+ * (no linked PR, unreachable device: `value` absent) still replaces a stale
+ * persisted row — a bare `undefined` / `null` response would leave it in place.
+ */
+export interface GitReviewRead<T> {
+ value?: T;
+}
+
+/** Serialized-JSON ceiling of one persisted row; larger values stay memory-only. */
+export const GIT_REVIEW_MAX_PERSISTED_BYTES = 512 * 1024;
+
+const fitsPersistCeiling = (value: unknown) => {
+ try {
+ return (JSON.stringify(value)?.length ?? 0) <= GIT_REVIEW_MAX_PERSISTED_BYTES;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Persist a value only when it fits the ceiling. An outsized value returns
+ * `null`, which also drops the older (smaller) row, so a reload never paints a
+ * value the live read has moved past.
+ */
+export const boundedPersist = <T>(data: T): T | null => (fitsPersistCeiling(data) ? data : null);
+
+const summarizePatch = ({
+ additions,
+ deletions,
+ filePath,
+ isBinary,
+ status,
+ truncated,
+}: GitWorkingTreePatch): GitWorkingTreePatch => ({
+ additions,
+ deletions,
+ filePath,
+ isBinary,
+ patch: '',
+ status,
+ truncated,
+});
+
+/**
+ * The persistable shape of a review read: file paths, statuses and +/- counts
+ * without diff text, which can run to megabytes and is cheap to re-read.
+ */
+export const toReviewPatchesSummary = (data: ReviewPatchesData): ReviewPatchesData => ({
+ baseRef: data.baseRef,
+ headRef: data.headRef,
+ mode: data.mode,
+ patches: data.patches.map(summarizePatch),
+ submodules: data.submodules?.map((sub) => ({ ...sub, patches: sub.patches.map(summarizePatch) })),
+ summaryOnly: true,
+});
+
+/**
+ * How the Review tab treats a painted read. A persisted summary is unconfirmed:
+ * the path may now hold different content, so destructive per-file actions
+ * (revert) wait for the live read (`isSummary`). Its expanded rows show a
+ * placeholder only while that read can still land (`diffPending`): a failed
+ * read leaves the summary in place, and the rows must then report the missing
+ * diff instead of loading forever.
+ */
+export const getReviewSummaryState = (data: ReviewPatchesData | undefined, error: unknown) => {
+ const isSummary = !!data?.summaryOnly;
+ return { diffPending: isSummary && !error, isSummary };
+};
+
+export interface GitReviewPatchesParams {
+ baseRef?: string;
+ /** Remote device; `undefined` reads this machine over Electron IPC. */
+ deviceId?: string;
+ mode: ReviewMode;
+ path: string;
+}
+
+export interface GitLinkedPRParams {
+ branch: string;
+ deviceId?: string;
+ path: string;
+}
+
+export interface GitPullRequestParams {
+ deviceId?: string;
+ number: number;
+ path: string;
+}
+
+export interface GitPullRequestMergeContextParams extends GitPullRequestParams {
+ baseRefName: string;
+ headRefOid: string;
+ repo: { name: string; owner: string };
+}
+
+export const gitReviewPatchesKey = ({ baseRef, deviceId, mode, path }: GitReviewPatchesParams) =>
+ joinKey(deviceId ?? LOCAL, path, mode, baseRef ?? '');
+
+export const gitLinkedPRKey = ({ branch, deviceId, path }: GitLinkedPRParams) =>
+ joinKey(deviceId ?? LOCAL, path, branch);
+
+export const gitPullRequestKey = ({ deviceId, number, path }: GitPullRequestParams) =>
+ joinKey(deviceId ?? LOCAL, path, number);
+
+export const gitPullRequestMergeContextKey = ({
+ baseRefName,
+ deviceId,
+ headRefOid,
+ number,
+ path,
+}: GitPullRequestMergeContextParams) =>
+ joinKey(deviceId ?? LOCAL, path, number, headRefOid, baseRefName);
+
+/** Repositories / PRs a user works on; old ones fall out of storage, not out of the app. */
+const persist = { maxEntries: 30 };
+
+/**
+ * Review tab diff. The store keeps the full diff; storage keeps only the
+ * path + line-count summary (`toReviewPatchesSummary`, applied by the slice).
+ */
+export const gitReviewPatchesResource = defineReplica<GitReviewPatchesParams, ReviewPatchesData>({
+ key: gitReviewPatchesKey,
+ name: 'deviceGitReviewPatches',
+ persist,
+ storage: 'indexedDB',
+ syncKey: ({ baseRef, deviceId, mode, path }) =>
+ deviceKeys.gitReviewPatches(deviceId ?? LOCAL, path, mode, baseRef ?? ''),
+ version: 1,
+});
+
+export const gitLinkedPRResource = defineReplica<
+ GitLinkedPRParams,
+ GitReviewRead<GitLinkedPRSummary>
+>({
+ key: gitLinkedPRKey,
+ name: 'deviceGitLinkedPR',
+ persist: { maxEntries: 50 },
+ storage: 'indexedDB',
+ syncKey: ({ branch, deviceId, path }) => deviceKeys.gitLinkedPR(deviceId ?? LOCAL, path, branch),
+ version: 1,
+});
+
+export const gitPullRequestDetailResource = defineReplica<
+ GitPullRequestParams,
+ GitReviewRead<DeviceGitPullRequestDetailResult>
+>({
+ key: gitPullRequestKey,
+ name: 'deviceGitPullRequestDetail',
+ persist,
+ storage: 'indexedDB',
+ syncKey: ({ deviceId, number, path }) =>
+ deviceKeys.gitPullRequestDetail(deviceId ?? LOCAL, path, number),
+ version: 1,
+});
+
+export const gitPullRequestActivityResource = defineReplica<
+ GitPullRequestParams,
+ GitReviewRead<DeviceGitPullRequestActivity>
+>({
+ key: gitPullRequestKey,
+ name: 'deviceGitPullRequestActivity',
+ persist,
+ storage: 'indexedDB',
+ syncKey: ({ deviceId, number, path }) =>
+ deviceKeys.gitPullRequestActivity(deviceId ?? LOCAL, path, number),
+ version: 1,
+});
+
+export const gitPullRequestMergeContextResource = defineReplica<
+ GitPullRequestMergeContextParams,
+ GitReviewRead<DeviceGitPullRequestMergeContext | null>
+>({
+ key: gitPullRequestMergeContextKey,
+ name: 'deviceGitPullRequestMergeContext',
+ persist,
+ storage: 'indexedDB',
+ syncKey: ({ baseRefName, deviceId, headRefOid, number, path }) =>
+ deviceKeys.gitPullRequestMergeContext(deviceId ?? LOCAL, path, number, headRefOid, baseRefName),
+ version: 1,
+});
diff --git a/src/store/device/gitReview/store.test.ts b/src/store/device/gitReview/store.test.ts
new file mode 100644
index 00000000000..2bb2649904c
--- /dev/null
+++ b/src/store/device/gitReview/store.test.ts
@@ -0,0 +1,618 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The Review / Pull Request tab reads are replicas: after a reload the last
+ * file list (paths + counts, no diff text) and the last PR detail / activity /
+ * merge context / linked PR paint from the persisted copy on the first frame,
+ * and the device read only confirms them.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';
+import type { DeviceGitPullRequestDetailResult } from '@lobechat/types';
+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, type ReplicaResource } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { gitService } from '@/services/git';
+
+import {
+ invalidateGitReviewCaches,
+ useFetchGitLinkedPR,
+ useFetchGitPullRequestActivity,
+ useFetchGitPullRequestDetail,
+ useFetchGitPullRequestMergeContext,
+ useReviewPatches,
+} from '../gitHooks';
+import {
+ getReviewSummaryState,
+ GIT_REVIEW_MAX_PERSISTED_BYTES,
+ gitLinkedPRResource,
+ gitPullRequestActivityResource,
+ gitPullRequestDetailResource,
+ gitPullRequestKey,
+ gitPullRequestMergeContextResource,
+ gitReviewPatchesResource,
+ type ReviewPatchesData,
+} from './projection';
+import { initialGitReviewState, useGitReviewStore } from './store';
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isDesktop: true,
+}));
+
+vi.mock('@/services/git', () => ({
+ gitService: {
+ getGitBranchDiff: vi.fn(),
+ getGitWorkingTreePatches: vi.fn(),
+ getLinkedPullRequest: vi.fn(),
+ getPullRequestActivity: vi.fn(),
+ getPullRequestDetail: vi.fn(),
+ getPullRequestMergeContext: 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 patch = (filePath: string, body: string): GitWorkingTreePatch => ({
+ additions: 3,
+ deletions: 1,
+ filePath,
+ isBinary: false,
+ patch: body,
+ status: 'modified',
+ truncated: false,
+});
+
+const detailResult: DeviceGitPullRequestDetailResult = {
+ detail: {
+ additions: 10,
+ author: 'octocat',
+ baseBehindBy: 0,
+ baseRefName: 'canary',
+ body: 'cached description',
+ changedFiles: 2,
+ checks: [{ name: 'ci', required: true, status: 'success' }],
+ comments: [],
+ commits: [],
+ deletions: 2,
+ headRefName: 'feat/x',
+ headRefOid: 'a'.repeat(40),
+ isCrossRepository: false,
+ isDraft: false,
+ mergeable: 'MERGEABLE',
+ mergeStateStatus: 'CLEAN',
+ number: 42,
+ repo: { name: 'repo', owner: 'octocat' },
+ reviewDecision: null,
+ reviews: [],
+ state: 'open',
+ title: 'Cached PR title',
+ url: 'https://github.com/octocat/repo/pull/42',
+ viewerCanBypass: false,
+ viewerCanWrite: true,
+ },
+ status: 'ok',
+};
+
+const REVIEW = {
+ baseRef: undefined,
+ deviceId: 'device-1',
+ mode: 'unstaged' as const,
+ path: '/repo',
+};
+const PR = { deviceId: 'device-1', number: 42, path: '/repo' };
+const LINKED = { branch: 'feat/x', deviceId: 'device-1', path: '/repo' };
+const MERGE = {
+ ...PR,
+ baseRefName: 'canary',
+ headRefOid: 'a'.repeat(40),
+ repo: { name: 'repo', owner: 'octocat' },
+};
+
+type AnyResource = ReplicaResource<any, any, any>;
+
+describe('Review / PR tab replicas', () => {
+ const scopes = new Set<string>();
+ const written: { params: unknown; resource: AnyResource }[] = [];
+ 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: AnyResource, params: unknown, data: unknown) => {
+ written.push({ params, resource });
+ return resource.storage!.set(
+ { queryKey: resource.storageKey(params), scope },
+ { data, updatedAt: 1 },
+ );
+ };
+ const readRow = async (resource: AnyResource, params: unknown) => {
+ written.push({ params, resource });
+ return (await resource.storage!.get({ queryKey: resource.storageKey(params), scope }))?.data;
+ };
+
+ beforeEach(() => {
+ useScope(`git-review-user-${randomUUID()}:personal`);
+ act(() => useGitReviewStore.setState(initialGitReviewState));
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ written.map(({ params, resource }) =>
+ resource.storage!.remove({ queryKey: resource.storageKey(params), scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ written.length = 0;
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ describe('Review tab', () => {
+ // Regression: the diff lived only in SWR's memory cache, so after a reload
+ // the Review tab showed a full-panel spinner until git answered.
+ it('paints the persisted file summary before the device answers', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/a.ts', ''), patch('src/b.ts', '')],
+ summaryOnly: true,
+ } satisfies ReviewPatchesData);
+ vi.mocked(gitService.getGitWorkingTreePatches).mockImplementation(pending);
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data?.patches).toHaveLength(2));
+ expect(result.current.data?.summaryOnly).toBe(true);
+ expect(result.current.data?.patches.map((p) => p.filePath)).toEqual(['src/a.ts', 'src/b.ts']);
+ // Something to paint: no spinner while the live read is pending.
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.isValidating).toBe(true);
+ });
+
+ // Regression: with a persisted summary and a failed live read (offline
+ // device), expanded rows kept their loading placeholder forever.
+ it('stops treating summary rows as pending once the live read fails', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/a.ts', '')],
+ summaryOnly: true,
+ } satisfies ReviewPatchesData);
+ vi.mocked(gitService.getGitWorkingTreePatches).mockRejectedValue(new Error('offline'));
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.isValidating).toBe(false);
+ expect(result.current.data?.summaryOnly).toBe(true);
+ expect(getReviewSummaryState(result.current.data, result.current.error)).toEqual({
+ diffPending: false,
+ // Still unconfirmed: revert stays disabled.
+ isSummary: true,
+ });
+ });
+
+ // Regression: an offline remote device resolves the patch read to
+ // `undefined`; it was turned into an empty working tree, so Review claimed
+ // "no changes" and overwrote the persisted summary.
+ it.each([
+ ['unstaged', 'getGitWorkingTreePatches'],
+ ['branch', 'getGitBranchDiff'],
+ ] as const)(
+ 'keeps the persisted %s summary when the device read is unknown',
+ async (mode, method) => {
+ const params = { ...REVIEW, mode };
+ const summary = {
+ mode,
+ patches: [patch('src/a.ts', '')],
+ summaryOnly: true,
+ } satisfies ReviewPatchesData;
+ await seed(gitReviewPatchesResource, params, summary);
+ vi.mocked(gitService[method]).mockResolvedValue(undefined);
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', mode, undefined, 'device-1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.patches.map((p) => p.filePath)).toEqual(['src/a.ts']);
+ expect(await readRow(gitReviewPatchesResource, params)).toEqual(summary);
+ },
+ );
+
+ it('treats summary rows as pending only while the live read can still land', () => {
+ const summary = { mode: 'unstaged', patches: [], summaryOnly: true } as ReviewPatchesData;
+ expect(getReviewSummaryState(summary, undefined)).toEqual({
+ diffPending: true,
+ isSummary: true,
+ });
+ expect(getReviewSummaryState({ mode: 'unstaged', patches: [] }, undefined)).toEqual({
+ diffPending: false,
+ isSummary: false,
+ });
+ expect(getReviewSummaryState(undefined, new Error('offline'))).toEqual({
+ diffPending: false,
+ isSummary: false,
+ });
+ });
+
+ it('replaces the summary with the live diff, and persists only the diff-free summary', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/old.ts', '')],
+ summaryOnly: true,
+ });
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({
+ patches: [patch('src/a.ts', '@@ -1 +1 @@\n-old\n+new')],
+ } as any);
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data?.patches[0]?.patch).toContain('+new'));
+ expect(result.current.data?.summaryOnly).toBeUndefined();
+ await waitFor(async () =>
+ expect(await readRow(gitReviewPatchesResource, REVIEW)).toEqual({
+ baseRef: undefined,
+ headRef: undefined,
+ mode: 'unstaged',
+ patches: [patch('src/a.ts', '')],
+ submodules: undefined,
+ summaryOnly: true,
+ }),
+ );
+ });
+
+ it('keeps an outsized summary memory-only and drops the older row', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/old.ts', '')],
+ summaryOnly: true,
+ });
+ const longPath = 'x'.repeat(1024);
+ const count = Math.ceil(GIT_REVIEW_MAX_PERSISTED_BYTES / 1024) + 1;
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({
+ patches: Array.from({ length: count }, (_, i) => patch(`${i}/${longPath}`, '+x')),
+ } as any);
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data?.patches).toHaveLength(count));
+ await waitFor(async () =>
+ expect(await readRow(gitReviewPatchesResource, REVIEW)).toBeUndefined(),
+ );
+ });
+
+ it('keys rows by device, so another device never paints this one', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/remote.ts', '')],
+ summaryOnly: true,
+ });
+ vi.mocked(gitService.getGitWorkingTreePatches).mockImplementation(pending);
+
+ const { result } = renderHook(() => useReviewPatches('/repo', 'unstaged'), { wrapper });
+ await waitFor(() => expect(gitService.getGitWorkingTreePatches).toHaveBeenCalled());
+
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('does not paint another identity’s rows', async () => {
+ await seed(gitReviewPatchesResource, REVIEW, {
+ mode: 'unstaged',
+ patches: [patch('src/theirs.ts', '')],
+ summaryOnly: true,
+ });
+ useScope(`git-review-user-${randomUUID()}:personal`);
+ vi.mocked(gitService.getGitWorkingTreePatches).mockImplementation(pending);
+
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+ await waitFor(() => expect(gitService.getGitWorkingTreePatches).toHaveBeenCalled());
+
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it('re-reads through the existing invalidation helper', async () => {
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({
+ patches: [patch('src/a.ts', '+1')],
+ } as any);
+ const { result } = renderHook(
+ () => useReviewPatches('/repo', 'unstaged', undefined, 'device-1'),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.data?.patches).toHaveLength(1));
+
+ vi.mocked(gitService.getGitWorkingTreePatches).mockResolvedValue({
+ patches: [patch('src/a.ts', '+1'), patch('src/b.ts', '+2')],
+ } as any);
+ await act(() =>
+ invalidateGitReviewCaches({ deviceId: 'device-1', dirPath: '/repo', mode: 'unstaged' }),
+ );
+
+ await waitFor(() => expect(result.current.data?.patches).toHaveLength(2));
+ });
+ });
+
+ describe('Pull Request tab', () => {
+ // Regression: the PR reads lived only in SWR's memory cache, so after a
+ // reload the PR tab body was a skeleton until `gh pr view` answered again.
+ it('paints the persisted linked PR, detail, activity and merge context before gh answers', async () => {
+ await Promise.all([
+ seed(gitLinkedPRResource, LINKED, {
+ value: {
+ pullRequest: { number: 42, state: 'open', title: 'Cached PR title', url: 'u' },
+ pullRequestStatus: 'ok',
+ },
+ }),
+ seed(gitPullRequestDetailResource, PR, { value: detailResult }),
+ seed(gitPullRequestActivityResource, PR, {
+ value: { comments: [{ author: 'a', body: 'cached comment' }], commits: [], reviews: [] },
+ }),
+ seed(gitPullRequestMergeContextResource, MERGE, {
+ value: {
+ baseBehindBy: 0,
+ requiredChecks: ['ci'],
+ viewerCanBypass: false,
+ viewerCanWrite: true,
+ },
+ }),
+ ]);
+ vi.mocked(gitService.getLinkedPullRequest).mockImplementation(pending);
+ vi.mocked(gitService.getPullRequestDetail).mockImplementation(pending);
+ vi.mocked(gitService.getPullRequestActivity).mockImplementation(pending);
+ vi.mocked(gitService.getPullRequestMergeContext).mockImplementation(pending);
+
+ const { result } = renderHook(
+ () => {
+ const linked = useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true);
+ const detail = useFetchGitPullRequestDetail('device-1', '/repo', 42);
+ const activity = useFetchGitPullRequestActivity('device-1', '/repo', 42);
+ const context = useFetchGitPullRequestMergeContext(
+ 'device-1',
+ '/repo',
+ detail.data?.detail ?? undefined,
+ );
+ return { activity, context, detail, linked };
+ },
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(result.current.detail.data?.detail?.title).toBe('Cached PR title'),
+ );
+ expect(result.current.detail.isLoading).toBe(false);
+ expect(result.current.detail.isValidating).toBe(true);
+ expect(result.current.linked.data?.pullRequest?.number).toBe(42);
+ await waitFor(() =>
+ expect(result.current.activity.data?.comments[0]?.body).toBe('cached comment'),
+ );
+ await waitFor(() => expect(result.current.context.data?.requiredChecks).toEqual(['ci']));
+ expect(gitService.getPullRequestDetail).toHaveBeenCalledWith({ ...PR, coreOnly: true });
+ });
+
+ // Regression: the PR tab mounts once the linked PR is known, and its own
+ // hydration then read the detail from storage — a skeleton frame in between.
+ it('reads the PR detail and activity from storage once the linked PR hydrates', async () => {
+ await Promise.all([
+ seed(gitLinkedPRResource, LINKED, {
+ value: {
+ pullRequest: { number: 42, state: 'open', title: 'Cached PR title', url: 'u' },
+ pullRequestStatus: 'ok',
+ },
+ }),
+ seed(gitPullRequestDetailResource, PR, { value: detailResult }),
+ seed(gitPullRequestActivityResource, PR, {
+ value: { comments: [{ author: 'a', body: 'cached comment' }], commits: [], reviews: [] },
+ }),
+ ]);
+ vi.mocked(gitService.getLinkedPullRequest).mockImplementation(pending);
+
+ // Only the linked-PR read is mounted: the PR tab is not rendered yet.
+ renderHook(() => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true), { wrapper });
+
+ const key = gitPullRequestKey(PR);
+ await waitFor(() =>
+ expect(
+ useGitReviewStore.getState().gitPullRequestDetailMap[key]?.value?.detail?.title,
+ ).toBe('Cached PR title'),
+ );
+ await waitFor(() =>
+ expect(
+ useGitReviewStore.getState().gitPullRequestActivityMap[key]?.value?.comments[0]?.body,
+ ).toBe('cached comment'),
+ );
+ expect(gitService.getPullRequestDetail).not.toHaveBeenCalled();
+ });
+
+ it('replaces the persisted detail with the gh read and persists it', async () => {
+ await seed(gitPullRequestDetailResource, PR, { value: detailResult });
+ const fresh: DeviceGitPullRequestDetailResult = {
+ ...detailResult,
+ detail: { ...detailResult.detail!, title: 'Renamed on GitHub' },
+ };
+ vi.mocked(gitService.getPullRequestDetail).mockResolvedValue(fresh);
+
+ const { result } = renderHook(() => useFetchGitPullRequestDetail('device-1', '/repo', 42), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.data?.detail?.title).toBe('Renamed on GitHub'));
+ await waitFor(async () =>
+ expect(await readRow(gitPullRequestDetailResource, PR)).toEqual({ value: fresh }),
+ );
+ });
+
+ it('lets an empty linked-PR answer replace a stale persisted PR', async () => {
+ await seed(gitLinkedPRResource, LINKED, {
+ value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' },
+ });
+ const none = { pullRequest: null, pullRequestStatus: 'ok' } as const;
+ vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue(none as any);
+
+ const { result } = renderHook(
+ () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data?.pullRequest).toBeNull());
+ await waitFor(async () =>
+ expect(await readRow(gitLinkedPRResource, LINKED)).toEqual({ value: none }),
+ );
+ });
+
+ // Regression: an offline remote device resolves the lookup to `undefined`;
+ // that was committed as "no PR", so the PR tab vanished and its persisted
+ // copy was overwritten.
+ it('keeps the persisted linked PR when the device read fails', async () => {
+ const cached = { value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' } };
+ await seed(gitLinkedPRResource, LINKED, cached);
+ vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue(undefined);
+
+ const { result } = renderHook(
+ () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.pullRequest?.number).toBe(42);
+ expect(await readRow(gitLinkedPRResource, LINKED)).toEqual(cached);
+ });
+
+ // Regression: a transient `gh` failure answers `{ pullRequest: null,
+ // status: 'error' }`; that was committed as "no PR" over the cached one.
+ it('keeps the persisted linked PR when the lookup reports an error', async () => {
+ const cached = { value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' } };
+ await seed(gitLinkedPRResource, LINKED, cached);
+ vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({
+ pullRequest: null,
+ pullRequestStatus: 'error',
+ } as any);
+
+ const { result } = renderHook(
+ () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.pullRequest?.number).toBe(42);
+ expect(result.current.isConfirmed).toBe(false);
+ expect(await readRow(gitLinkedPRResource, LINKED)).toEqual(cached);
+ });
+
+ // A persisted row paints, but only the device's answer makes it actionable.
+ it('reports a hydrated detail as unconfirmed until gh answers', async () => {
+ await seed(gitPullRequestDetailResource, PR, { value: detailResult });
+ let answer!: (value: DeviceGitPullRequestDetailResult) => void;
+ vi.mocked(gitService.getPullRequestDetail).mockReturnValue(
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ );
+
+ const { result } = renderHook(() => useFetchGitPullRequestDetail('device-1', '/repo', 42), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.data?.detail?.title).toBe('Cached PR title'));
+ expect(result.current.isConfirmed).toBe(false);
+
+ await act(async () => answer(detailResult));
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ });
+
+ // Regression: the service maps a failed remote detail read to
+ // `{ detail: null, status: 'error' }`, which replaced the persisted PR.
+ it('keeps the persisted detail when the detail read fails', async () => {
+ await seed(gitPullRequestDetailResource, PR, { value: detailResult });
+ vi.mocked(gitService.getPullRequestDetail).mockResolvedValue({
+ detail: null,
+ status: 'error',
+ });
+
+ const { result } = renderHook(() => useFetchGitPullRequestDetail('device-1', '/repo', 42), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.detail?.title).toBe('Cached PR title');
+ expect(await readRow(gitPullRequestDetailResource, PR)).toEqual({ value: detailResult });
+ });
+
+ // Regression: an unavailable remote device answers the merge context with
+ // `null`; it was committed and persisted over the cached permission and
+ // required-check context.
+ it('keeps the persisted merge context when the device read fails', async () => {
+ const cached = {
+ value: {
+ baseBehindBy: 0,
+ requiredChecks: ['ci'],
+ viewerCanBypass: false,
+ viewerCanWrite: true,
+ },
+ };
+ await seed(gitPullRequestMergeContextResource, MERGE, cached);
+ vi.mocked(gitService.getPullRequestMergeContext).mockResolvedValue(null);
+
+ const { result } = renderHook(
+ () => useFetchGitPullRequestMergeContext('device-1', '/repo', detailResult.detail!),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.requiredChecks).toEqual(['ci']);
+ expect(await readRow(gitPullRequestMergeContextResource, MERGE)).toEqual(cached);
+ });
+
+ it('does not read a PR for a non-GitHub repo', async () => {
+ const { result } = renderHook(
+ () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', false),
+ { wrapper },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(gitService.getLinkedPullRequest).not.toHaveBeenCalled();
+ expect(result.current.isLoading).toBe(false);
+ });
+ });
+});
diff --git a/src/store/device/gitReview/store.ts b/src/store/device/gitReview/store.ts
new file mode 100644
index 00000000000..073d3931dc1
--- /dev/null
+++ b/src/store/device/gitReview/store.ts
@@ -0,0 +1,216 @@
+import type {
+ DeviceGitPullRequestActivity,
+ DeviceGitPullRequestDetailResult,
+ DeviceGitPullRequestMergeContext,
+} from '@lobechat/types';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+import { type GitLinkedPRSummary, gitService } from '@/services/git';
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+import {
+ boundedPersist,
+ type GitLinkedPRParams,
+ gitLinkedPRResource,
+ gitPullRequestActivityResource,
+ gitPullRequestDetailResource,
+ gitPullRequestKey,
+ type GitPullRequestMergeContextParams,
+ gitPullRequestMergeContextResource,
+ type GitPullRequestParams,
+ type GitReviewPatchesParams,
+ gitReviewPatchesResource,
+ type GitReviewRead,
+ type ReviewPatchesData,
+ toReviewPatchesSummary,
+} from './projection';
+
+type LinkedPRRead = GitReviewRead<GitLinkedPRSummary>;
+type DetailRead = GitReviewRead<DeviceGitPullRequestDetailResult>;
+type ActivityRead = GitReviewRead<DeviceGitPullRequestActivity>;
+type MergeContextRead = GitReviewRead<DeviceGitPullRequestMergeContext | null>;
+
+export interface GitReviewStoreState {
+ /** `gitLinkedPRKey(params)` → PR linked to a branch. */
+ gitLinkedPRMap: Record<string, LinkedPRRead>;
+ gitLinkedPRReplica: ReplicaState<LinkedPRRead>;
+ /** `gitPullRequestKey(params)` → comments / reviews / commits. */
+ gitPullRequestActivityMap: Record<string, ActivityRead>;
+ gitPullRequestActivityReplica: ReplicaState<ActivityRead>;
+ /** `gitPullRequestKey(params)` → PR core detail. */
+ gitPullRequestDetailMap: Record<string, DetailRead>;
+ gitPullRequestDetailReplica: ReplicaState<DetailRead>;
+ /** `gitPullRequestMergeContextKey(params)` → permission / protection / base drift. */
+ gitPullRequestMergeContextMap: Record<string, MergeContextRead>;
+ gitPullRequestMergeContextReplica: ReplicaState<MergeContextRead>;
+ /** `gitReviewPatchesKey(params)` → review diff (a diff-free summary after a reload). */
+ gitReviewPatchesMap: Record<string, ReviewPatchesData>;
+ gitReviewPatchesReplica: ReplicaState<ReviewPatchesData>;
+}
+
+export const initialGitReviewState: GitReviewStoreState = {
+ gitLinkedPRMap: {},
+ gitLinkedPRReplica: createReplicaState(),
+ gitPullRequestActivityMap: {},
+ gitPullRequestActivityReplica: createReplicaState(),
+ gitPullRequestDetailMap: {},
+ gitPullRequestDetailReplica: createReplicaState(),
+ gitPullRequestMergeContextMap: {},
+ gitPullRequestMergeContextReplica: createReplicaState(),
+ gitReviewPatchesMap: {},
+ gitReviewPatchesReplica: createReplicaState(),
+};
+
+/**
+ * A remote device read resolves to `undefined` when the gateway or the device
+ * RPC fails (the local IPC always answers). That is an unknown result, not an
+ * empty one: reject it so the replica keeps the persisted copy instead of
+ * committing — and persisting — "no changes" / "no PR" over it.
+ */
+const requireAnswer = <T>(value: T | undefined, what: string): T => {
+ if (value === undefined) throw new Error(`Unable to load ${what}`);
+ return value;
+};
+
+const fetchReviewPatches = async ({
+ baseRef,
+ deviceId,
+ mode,
+ path,
+}: GitReviewPatchesParams): Promise<ReviewPatchesData> => {
+ if (mode === 'unstaged') {
+ const result = requireAnswer(
+ await gitService.getGitWorkingTreePatches({ deviceId, path }),
+ 'working tree changes',
+ );
+ return { mode: 'unstaged', patches: result.patches ?? [], submodules: result.submodules };
+ }
+ const result = requireAnswer(
+ await gitService.getGitBranchDiff({ baseRef, deviceId, path }),
+ 'branch diff',
+ );
+ return {
+ baseRef: result.baseRef,
+ headRef: result.headRef,
+ mode: 'branch',
+ patches: result.patches ?? [],
+ submodules: result.submodules,
+ };
+};
+
+const createSlices = (
+ set: (partial: Partial<GitReviewStore>, replace?: false, action?: any) => void,
+ get: () => GitReviewStore,
+) => ({
+ linkedPR: createReplicaSlice(gitLinkedPRResource, {
+ actionPrefix: 'gitReview/linkedPR',
+ // "No PR" is an answer (`pullRequest: null`, status `ok`); `undefined` (a
+ // failed remote read) and status `error` (a transient `gh` failure) are not.
+ // `gh-missing` stays an answer: the composer shows it.
+ fetcher: async (params: GitLinkedPRParams) => {
+ const value = requireAnswer(
+ await gitService.getLinkedPullRequest(params),
+ 'linked pull request',
+ );
+ if (value.pullRequestStatus === 'error')
+ throw new Error('Unable to load linked pull request');
+ return { value };
+ },
+ get,
+ set,
+ stateKey: 'gitLinkedPRReplica',
+ view: recordLens<GitReviewStore, LinkedPRRead>('gitLinkedPRMap'),
+ }),
+ pullRequestActivity: createReplicaSlice(gitPullRequestActivityResource, {
+ actionPrefix: 'gitReview/pullRequestActivity',
+ fetcher: async (params: GitPullRequestParams) => ({
+ value: await gitService.getPullRequestActivity(params),
+ }),
+ get,
+ set,
+ stateKey: 'gitPullRequestActivityReplica',
+ // Comment bodies are unbounded.
+ toPersisted: boundedPersist,
+ view: recordLens<GitReviewStore, ActivityRead>('gitPullRequestActivityMap'),
+ }),
+ pullRequestDetail: createReplicaSlice(gitPullRequestDetailResource, {
+ actionPrefix: 'gitReview/pullRequestDetail',
+ fetcher: async (params: GitPullRequestParams) => {
+ const value = await gitService.getPullRequestDetail({ ...params, coreOnly: true });
+ // A failed lookup (including a remote read the service maps to
+ // `status: 'error'`) must not replace the persisted PR.
+ if (value.status === 'error') throw new Error('Unable to load pull request');
+ return { value };
+ },
+ get,
+ set,
+ stateKey: 'gitPullRequestDetailReplica',
+ // The PR description is unbounded.
+ toPersisted: boundedPersist,
+ view: recordLens<GitReviewStore, DetailRead>('gitPullRequestDetailMap'),
+ }),
+ pullRequestMergeContext: createReplicaSlice(gitPullRequestMergeContextResource, {
+ actionPrefix: 'gitReview/pullRequestMergeContext',
+ // The local read always answers; `null` is the service's mapping of a
+ // failed remote read and must not replace the persisted context.
+ fetcher: async (params: GitPullRequestMergeContextParams) => {
+ const value = await gitService.getPullRequestMergeContext(params);
+ if (value === null) throw new Error('Unable to load pull request merge context');
+ return { value };
+ },
+ get,
+ set,
+ stateKey: 'gitPullRequestMergeContextReplica',
+ view: recordLens<GitReviewStore, MergeContextRead>('gitPullRequestMergeContextMap'),
+ }),
+ reviewPatches: createReplicaSlice(gitReviewPatchesResource, {
+ actionPrefix: 'gitReview/reviewPatches',
+ fetcher: fetchReviewPatches,
+ get,
+ set,
+ stateKey: 'gitReviewPatchesReplica',
+ // Diff text can run to megabytes and is cheap to re-read: persist only the
+ // file list + counts, and nothing when even that is outsized.
+ toPersisted: (data) => boundedPersist(toReviewPatchesSummary(data)),
+ view: recordLens<GitReviewStore, ReviewPatchesData>('gitReviewPatchesMap'),
+ }),
+});
+
+type GitReviewSlices = ReturnType<typeof createSlices>;
+
+export interface GitReviewStore extends GitReviewStoreState {
+ /** @internal The replica slices; read through the hooks in `gitHooks.ts`. */
+ slices: GitReviewSlices;
+}
+
+const devtools = createDevtools('gitReview');
+
+export const useGitReviewStore = createWithEqualityFn<GitReviewStore>()(
+ devtools((set, get) => ({
+ ...initialGitReviewState,
+ slices: createSlices(set, get),
+ })),
+ shallow,
+);
+
+expose('gitReview', useGitReviewStore);
+
+/**
+ * Read a PR's persisted detail and activity into memory ahead of the PR tab's
+ * own hydration. Rows already in memory are left alone.
+ */
+export const warmPullRequestReplicas = (params: GitPullRequestParams) => {
+ const { gitPullRequestActivityMap, gitPullRequestDetailMap, slices } =
+ useGitReviewStore.getState();
+ const key = gitPullRequestKey(params);
+ if (!gitPullRequestDetailMap[key]) void slices.pullRequestDetail.hydrate(params);
+ if (!gitPullRequestActivityMap[key]) void slices.pullRequestActivity.hydrate(params);
+};