Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(review): 避免 Agent 工作时重复重建 Diff

david68a867ba393a
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
index ce63589985..293d650640 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/__tests__/PlainUnifiedDiff.test.ts
@@ -13,7 +13,13 @@ vi.mock('react-i18next', () => ({
import { buildHunkRows, hunkActionRevealClass, PlainUnifiedDiff } from '../PlainUnifiedDiff';
import type { FileDiff, Hunk } from '@/lib/gitReview.types';
-import { buildSplitRows, buildUnifiedRows, shouldVirtualizeDiffRows, shouldVirtualizeFileList } from '../diffRows';
+import {
+ buildSplitRows,
+ buildUnifiedRows,
+ countDiffRows,
+ shouldVirtualizeDiffRows,
+ shouldVirtualizeFileList,
+} from '../diffRows';
import {
collectHighlightLines,
HIGHLIGHT_MAX_DIFF_LINES,
@@ -528,6 +534,27 @@ describe('PlainUnifiedDiff performance helpers', () => {
expect(shouldVirtualizeDiffRows(201)).toBe(true);
expect(shouldVirtualizeFileList(100)).toBe(false);
expect(shouldVirtualizeFileList(101)).toBe(true);
+ expect(shouldVirtualizeFileList(13, 200)).toBe(false);
+ expect(shouldVirtualizeFileList(13, 201)).toBe(true);
+ });
+
+ it('virtualizes a small file list when its expanded eager rows exceed the shared budget', () => {
+ expect(shouldVirtualizeFileList(13, 13 * 172)).toBe(true);
+ });
+
+ it('counts unified and paired split rows without building render rows', () => {
+ const sourceHunk = {
+ ...hunk(0, 8, 3),
+ lines: [
+ line(0, 'context', 'before', 8, 8),
+ line(1, 'delete', 'old', 9, null),
+ line(2, 'add', 'new', null, 9),
+ line(3, 'context', 'after', 10, 10),
+ ],
+ };
+
+ expect(countDiffRows([sourceHunk], 'unified')).toBe(5);
+ expect(countDiffRows([sourceHunk], 'split')).toBe(4);
});
it('virtualizes files shaped like the two-file whole-file rewrite regression', () => {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
index 164a8b9a7e..9932ca38f8 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts
@@ -3,12 +3,18 @@ import type { DiffLine, Hunk } from '@/lib/gitReview.types';
export type DiffViewMode = 'unified' | 'split';
export type HunkRenderRow =
- | { type: 'separator'; key: string; count: number }
- | { type: 'hunk'; key: string; hunk: Hunk };
+ { type: 'separator'; key: string; count: number } | { type: 'hunk'; key: string; hunk: Hunk };
export type UnifiedDiffRow =
| { type: 'separator'; key: string; count: number }
- | { type: 'line'; key: string; hunk: Hunk; line: DiffLine; originalLineIndex: number; hunkActionAnchor?: HunkActionAnchor };
+ | {
+ type: 'line';
+ key: string;
+ hunk: Hunk;
+ line: DiffLine;
+ originalLineIndex: number;
+ hunkActionAnchor?: HunkActionAnchor;
+ };
export interface SplitDiffCell {
line: DiffLine;
@@ -41,11 +47,21 @@ export interface HunkActionAnchor {
// 500-row cutoff could otherwise mount roughly a thousand diff rows at once.
export const DIFF_ROW_VIRTUAL_THRESHOLD = 200;
export const FILE_LIST_VIRTUAL_THRESHOLD = 100;
+export const EAGER_EXPANDED_DIFF_ROW_THRESHOLD = 200;
function oldEndLine(hunk: Hunk): number {
return hunk.oldLines > 0 ? hunk.oldStart + hunk.oldLines - 1 : hunk.oldStart;
}
+function hiddenLineCountBeforeHunk(hunks: readonly Hunk[], index: number): number {
+ const hunk = hunks[index];
+ return index === 0
+ ? hunk.oldStart > 1
+ ? hunk.oldStart - 1
+ : 0
+ : hunk.oldStart - oldEndLine(hunks[index - 1]) - 1;
+}
+
function lastChangedLineIndex(hunk: Hunk): number {
for (let i = hunk.lines.length - 1; i >= 0; i -= 1) {
if (hunk.lines[i].type !== 'context') return i;
@@ -63,7 +79,8 @@ function isChangedCell(cell: SplitDiffCell | null): boolean {
function lastChangedSplitRowIndex(rows: readonly SplitDiffRow[]): number {
for (let i = rows.length - 1; i >= 0; i -= 1) {
const row = rows[i];
- if (row.type === 'split-line' && (isChangedCell(row.left) || isChangedCell(row.right))) return i;
+ if (row.type === 'split-line' && (isChangedCell(row.left) || isChangedCell(row.right)))
+ return i;
}
return rows.length - 1;
}
@@ -72,9 +89,7 @@ export function buildHunkRows(hunks: readonly Hunk[]): HunkRenderRow[] {
const rows: HunkRenderRow[] = [];
for (let i = 0; i < hunks.length; i += 1) {
const hunk = hunks[i];
- const hiddenCount = i === 0
- ? hunk.oldStart > 1 ? hunk.oldStart - 1 : 0
- : hunk.oldStart - oldEndLine(hunks[i - 1]) - 1;
+ const hiddenCount = hiddenLineCountBeforeHunk(hunks, i);
if (hiddenCount > 0) {
rows.push({ type: 'separator', key: `sep-${hunk.index}`, count: hiddenCount });
}
@@ -130,15 +145,62 @@ export function buildDiffRows(hunks: readonly Hunk[], mode: DiffViewMode): DiffR
return mode === 'split' ? buildSplitRows(hunks) : buildUnifiedRows(hunks);
}
+/** Counts rendered rows without allocating the row objects used by the diff viewer. */
+export function countDiffRows(
+ hunks: readonly Hunk[],
+ mode: DiffViewMode,
+ stopAfter = Number.POSITIVE_INFINITY,
+): number {
+ let count = 0;
+ for (let hunkIndex = 0; hunkIndex < hunks.length; hunkIndex += 1) {
+ if (hiddenLineCountBeforeHunk(hunks, hunkIndex) > 0) count += 1;
+ if (count > stopAfter) return count;
+ const hunk = hunks[hunkIndex];
+ if (mode === 'unified') {
+ count += hunk.lines.length;
+ if (count > stopAfter) return count;
+ continue;
+ }
+ let lineIndex = 0;
+ while (lineIndex < hunk.lines.length) {
+ if (hunk.lines[lineIndex].type === 'context') {
+ count += 1;
+ lineIndex += 1;
+ if (count > stopAfter) return count;
+ continue;
+ }
+ let deletes = 0;
+ let adds = 0;
+ while (lineIndex < hunk.lines.length && hunk.lines[lineIndex].type !== 'context') {
+ if (hunk.lines[lineIndex].type === 'delete') deletes += 1;
+ else adds += 1;
+ lineIndex += 1;
+ }
+ count += Math.max(deletes, adds);
+ if (count > stopAfter) return count;
+ }
+ }
+ return count;
+}
+
export function shouldVirtualizeDiffRows(rowCount: number): boolean {
return rowCount > DIFF_ROW_VIRTUAL_THRESHOLD;
}
-export function shouldVirtualizeFileList(fileCount: number): boolean {
- return fileCount > FILE_LIST_VIRTUAL_THRESHOLD;
+export function shouldVirtualizeFileList(
+ fileCount: number,
+ eagerExpandedDiffRowCount = 0,
+): boolean {
+ return (
+ fileCount > FILE_LIST_VIRTUAL_THRESHOLD ||
+ eagerExpandedDiffRowCount > EAGER_EXPANDED_DIFF_ROW_THRESHOLD
+ );
}
-export function estimateDiffRowsMinWidthCh(rows: readonly DiffRenderRow[], mode: DiffViewMode): number {
+export function estimateDiffRowsMinWidthCh(
+ rows: readonly DiffRenderRow[],
+ mode: DiffViewMode,
+): number {
let max = mode === 'split' ? 88 : 40;
for (const row of rows) {
if (row.type === 'line') {
@@ -203,7 +265,10 @@ export function buildPairedChangedLinesForHunk(hunk: Hunk): PairedChangedLines[]
return pairs;
}
-function collectChangedRun(hunk: Hunk, startIndex: number): { pairs: PairedChangedLines[]; nextIndex: number } {
+function collectChangedRun(
+ hunk: Hunk,
+ startIndex: number,
+): { pairs: PairedChangedLines[]; nextIndex: number } {
const deletes: DiffLine[] = [];
const adds: DiffLine[] = [];
let i = startIndex;
@@ -216,7 +281,10 @@ function collectChangedRun(hunk: Hunk, startIndex: number): { pairs: PairedChang
return { pairs: pairChangedLines(deletes, adds), nextIndex: i };
}
-function pairChangedLines(deletes: readonly DiffLine[], adds: readonly DiffLine[]): PairedChangedLines[] {
+function pairChangedLines(
+ deletes: readonly DiffLine[],
+ adds: readonly DiffLine[],
+): PairedChangedLines[] {
const count = Math.max(deletes.length, adds.length);
const pairs: PairedChangedLines[] = [];
for (let i = 0; i < count; i += 1) {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
index 2b30d1f048..42be9856fe 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
@@ -92,7 +92,13 @@ import type { ReviewState } from './index';
import { getReviewDiffsExpanded, setReviewDiffsExpanded } from './diffExpansionPreference';
import { PlainUnifiedDiff, type DiffViewMode } from './DiffViewer/PlainUnifiedDiff';
import { MarkdownDiffPreview } from './DiffViewer/MarkdownDiffPreview';
-import { shouldVirtualizeFileList } from './DiffViewer/diffRows';
+import {
+ countDiffRows,
+ DIFF_ROW_VIRTUAL_THRESHOLD,
+ shouldVirtualizeDiffRows,
+ shouldVirtualizeFileList,
+} from './DiffViewer/diffRows';
+
import {
buildFilteredReviewFileTree,
filterReviewFileJumpResults,
@@ -2916,6 +2922,22 @@ export interface WriteActionProps {
onSectionDiscard?: () => void;
}
+export function countEagerExpandedDiffRows(
+ diffs: readonly FileDiff[],
+ expandedSet: ReadonlySet<string>,
+ viewMode: DiffViewMode,
+): number {
+ if (shouldVirtualizeFileList(diffs.length)) return 0;
+ let count = 0;
+ for (const diff of diffs) {
+ if (!expandedSet.has(diff.id)) continue;
+ const rowCount = countDiffRows(diff.hunks, viewMode, DIFF_ROW_VIRTUAL_THRESHOLD);
+ if (!shouldVirtualizeDiffRows(rowCount)) count += rowCount;
+ if (shouldVirtualizeFileList(0, count)) break;
+ }
+ return count;
+}
+
function DiffList({
diffs,
expandedSet,
@@ -2976,12 +2998,17 @@ function DiffList({
(writeAction?.sectionAction && writeAction.onSectionAction) ||
(writeAction?.sectionDiscardVisible && writeAction.onSectionDiscard),
);
- const virtualized = shouldVirtualizeFileList(diffs.length);
+ const eagerExpandedDiffRowCount = useMemo(
+ () => countEagerExpandedDiffRows(diffs, expandedSet, viewMode),
+ [diffs, expandedSet, viewMode],
+ );
+ const virtualizedByExpandedRows = shouldVirtualizeFileList(0, eagerExpandedDiffRowCount);
+ const virtualized = shouldVirtualizeFileList(diffs.length, eagerExpandedDiffRowCount);
const fileVirtualizer = useVirtualizer({
count: diffs.length,
getScrollElement: () => parentRef.current,
estimateSize: (index) => (expandedSet.has(diffs[index]?.id) ? 360 : 45),
- overscan: 8,
+ overscan: virtualizedByExpandedRows ? 2 : 8,
getItemKey: (index) => diffs[index]?.id ?? index,
});
const fileTreeVisibility = getReviewFileTreeVisibility({
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
index 42f2a0c4a2..7640fae407 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
@@ -21,6 +21,7 @@ import {
buildLastTurnCappedData,
canUsePatchBasedReviewActions,
CappedSourceView,
+ countEagerExpandedDiffRows,
descriptorForReviewSource,
discardForReviewDiff,
filterWhitespaceHiddenDiffs,
@@ -142,6 +143,60 @@ describe('ReviewTabBody Last turn actions', () => {
});
});
+describe('ReviewTabBody expanded diff budget', () => {
+ function diffWithRows(path: string, rowCount: number): FileDiff {
+ return diff('unstaged', path, {
+ hunks: [
+ {
+ index: 0,
+ header: `@@ -1,${rowCount} +1,${rowCount} @@`,
+ oldStart: 1,
+ oldLines: rowCount,
+ newStart: 1,
+ newLines: rowCount,
+ section: '',
+ lines: Array.from({ length: rowCount }, (_, index) => ({
+ index,
+ type: 'context' as const,
+ content: `line ${index}`,
+ raw: ` line ${index}`,
+ oldLineNumber: index + 1,
+ newLineNumber: index + 1,
+ originalLineNumber: index + 1,
+ selectable: false,
+ noTrailingNewLine: false,
+ })),
+ selectableLines: [],
+ raw: '',
+ },
+ ],
+ });
+ }
+
+ it('adds only expanded diffs that do not already virtualize their own rows', () => {
+ const first = diffWithRows('first.ts', 120);
+ const second = diffWithRows('second.ts', 120);
+ const selfVirtualized = diffWithRows('large.ts', 201);
+
+ expect(countEagerExpandedDiffRows([first, second], new Set([first.id]), 'unified')).toBe(120);
+ expect(
+ countEagerExpandedDiffRows(
+ [first, second, selfVirtualized],
+ new Set([first.id, second.id, selfVirtualized.id]),
+ 'unified',
+ ),
+ ).toBe(240);
+ });
+
+ it('skips expanded-row scanning when file count already virtualizes the outer list', () => {
+ const diffs = Array.from({ length: 101 }, (_, index) => diff('unstaged', `${index}.ts`));
+
+ expect(countEagerExpandedDiffRows(diffs, new Set(diffs.map((item) => item.id)), 'unified')).toBe(
+ 0,
+ );
+ });
+});
+
describe('ReviewTabBody hunk action eligibility', () => {
it('keeps patch-based hunk actions available for modified text diffs', () => {
expect(partialAllowed(diff('unstaged', 'file.txt'))).toBe(true);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useLastTurnFilter.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useLastTurnFilter.test.ts
index 15332bfbe6..c98de66e0f 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useLastTurnFilter.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useLastTurnFilter.test.ts
@@ -1,9 +1,33 @@
// @vitest-environment jsdom
-import { describe, expect, it } from 'vitest';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatMessage } from '@/lib/makerChatStore';
-import { absoluteToRepoRelative, collectLastTurnPaths } from '../useLastTurnFilter';
+
+const chat = vi.hoisted(() => {
+ const listeners = new Set<() => void>();
+ return {
+ listeners,
+ snapshot: { messages: [] as ChatMessage[] },
+ };
+});
+
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ getSnapshot: () => chat.snapshot,
+ subscribe: (_sessionId: string, listener: () => void) => {
+ chat.listeners.add(listener);
+ return () => chat.listeners.delete(listener);
+ },
+ },
+}));
+
+import {
+ absoluteToRepoRelative,
+ collectLastTurnPaths,
+ useLastTurnFilter,
+} from '../useLastTurnFilter';
function msg(partial: Partial<ChatMessage>): ChatMessage {
return {
@@ -14,6 +38,22 @@ function msg(partial: Partial<ChatMessage>): ChatMessage {
} as ChatMessage;
}
+function publish(messages: ChatMessage[]): void {
+ chat.snapshot = { messages };
+ act(() => {
+ for (const listener of chat.listeners) listener();
+ });
+}
+
+beforeEach(() => {
+ chat.listeners.clear();
+ chat.snapshot = { messages: [] };
+});
+
+afterEach(() => {
+ cleanup();
+});
+
describe('useLastTurnFilter path collection', () => {
it('converts absolute paths to repo-relative paths', () => {
expect(absoluteToRepoRelative('/repo/src/app.ts', '/repo')).toBe('src/app.ts');
@@ -21,50 +61,128 @@ describe('useLastTurnFilter path collection', () => {
});
it('collects Codex file_change paths from absolute and repo-relative change entries', () => {
- const paths = collectLastTurnPaths([
- msg({ role: 'user', content: 'change files' }),
- msg({
- role: 'tool_use',
- toolName: 'file_change',
- toolInput: {
- changes: [
- { path: '/repo/src/absolute.ts', kind: { type: 'update' } },
- { path: 'src/relative.ts', kind: { type: 'add' } },
- { path: 'src/delete.ts', kind: { type: 'delete' } },
- ],
- },
- }),
- ], '/repo');
+ const paths = collectLastTurnPaths(
+ [
+ msg({ role: 'user', content: 'change files' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'file_change',
+ toolInput: {
+ changes: [
+ { path: '/repo/src/absolute.ts', kind: { type: 'update' } },
+ { path: 'src/relative.ts', kind: { type: 'add' } },
+ { path: 'src/delete.ts', kind: { type: 'delete' } },
+ ],
+ },
+ }),
+ ],
+ '/repo',
+ );
expect([...paths].sort()).toEqual(['src/absolute.ts', 'src/delete.ts', 'src/relative.ts']);
});
it('collects defensive move path fields from Codex update changes', () => {
- const paths = collectLastTurnPaths([
- msg({ role: 'user', content: 'move files' }),
- msg({
- role: 'tool_use',
- toolName: 'file_change',
- toolInput: {
- changes: [
- { path: 'src/old.ts', kind: { type: 'update', move_path: 'src/new.ts' } },
- { path: 'docs/old.md', kind: { type: 'update', movePath: '/repo/docs/new.md' } },
- ],
- },
- }),
- ], '/repo');
+ const paths = collectLastTurnPaths(
+ [
+ msg({ role: 'user', content: 'move files' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'file_change',
+ toolInput: {
+ changes: [
+ { path: 'src/old.ts', kind: { type: 'update', move_path: 'src/new.ts' } },
+ { path: 'docs/old.md', kind: { type: 'update', movePath: '/repo/docs/new.md' } },
+ ],
+ },
+ }),
+ ],
+ '/repo',
+ );
expect([...paths].sort()).toEqual(['docs/new.md', 'docs/old.md', 'src/new.ts', 'src/old.ts']);
});
it('only scans messages after the latest user turn', () => {
- const paths = collectLastTurnPaths([
- msg({ role: 'user', content: 'first' }),
- msg({ role: 'tool_use', toolName: 'file_change', toolInput: { changes: [{ path: 'old.ts' }] } }),
- msg({ role: 'user', content: 'second' }),
- msg({ role: 'tool_use', toolName: 'file_change', toolInput: { changes: [{ path: 'new.ts' }] } }),
- ], '/repo');
+ const paths = collectLastTurnPaths(
+ [
+ msg({ role: 'user', content: 'first' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'file_change',
+ toolInput: { changes: [{ path: 'old.ts' }] },
+ }),
+ msg({ role: 'user', content: 'second' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'file_change',
+ toolInput: { changes: [{ path: 'new.ts' }] },
+ }),
+ ],
+ '/repo',
+ );
expect([...paths]).toEqual(['new.ts']);
});
});
+
+describe('useLastTurnFilter subscriptions', () => {
+ it('does not render again when streaming text changes but the last-turn paths stay the same', () => {
+ const messages = [
+ msg({ role: 'user', content: 'change a file' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/src/app.ts' },
+ }),
+ msg({ role: 'assistant', content: 'Starting' }),
+ ];
+ chat.snapshot = { messages };
+ let renders = 0;
+ const view = renderHook(() => {
+ renders += 1;
+ return useLastTurnFilter('session-1', '/repo');
+ });
+ const initialResult = view.result.current;
+
+ publish([
+ ...messages.slice(0, -1),
+ { ...messages.at(-1)!, content: 'Starting and still working' },
+ ]);
+
+ expect(renders).toBe(1);
+ expect(view.result.current).toBe(initialResult);
+ expect([...view.result.current]).toEqual(['src/app.ts']);
+ });
+
+ it('renders again when the last-turn path set changes', () => {
+ const messages = [
+ msg({ role: 'user', content: 'change files' }),
+ msg({
+ role: 'tool_use',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/src/app.ts' },
+ }),
+ ];
+ chat.snapshot = { messages };
+ let renders = 0;
+ const view = renderHook(() => {
+ renders += 1;
+ return useLastTurnFilter('session-1', '/repo');
+ });
+ const initialResult = view.result.current;
+
+ publish([
+ ...messages,
+ msg({
+ role: 'tool_use',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/src/new.ts' },
+ }),
+ ]);
+
+ expect(renders).toBe(2);
+ expect(view.result.current).not.toBe(initialResult);
+ expect([...view.result.current].sort()).toEqual(['src/app.ts', 'src/new.ts']);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewGitState.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewGitState.test.ts
index 380b281ceb..1189197c63 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewGitState.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewGitState.test.ts
@@ -4,8 +4,20 @@ import { act, render, screen, waitFor } from '@testing-library/react';
import { createElement } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { ReviewCommitDiffData, ReviewDirtySummary, ReviewFileDiffData, ReviewFileDiffRequest } from '@/lib/gitReview.types';
-import { useReviewCommitDiff, useReviewDirtySummary, useReviewFileDiff, useReviewFileDiffs } from '../useReviewGitState';
+import type {
+ ReviewCommitDiffData,
+ ReviewDirtySummary,
+ ReviewFileDiffData,
+ ReviewFileDiffRequest,
+} from '@/lib/gitReview.types';
+import type { SessionStatusInfo } from '@/lib/makerChatStore';
+import {
+ subscribeReviewRefreshOnTurnEnd,
+ useReviewCommitDiff,
+ useReviewDirtySummary,
+ useReviewFileDiff,
+ useReviewFileDiffs,
+} from '../useReviewGitState';
function deferred<T>() {
let resolve!: (value: T) => void;
@@ -17,12 +29,26 @@ function deferred<T>() {
function Probe({ sessionId, oid }: { sessionId: string; oid: string }) {
const state = useReviewCommitDiff(sessionId, oid);
- return createElement('div', { 'data-testid': 'state' }, `${state.data?.commitOid ?? 'null'}|${state.loading ? 'loading' : 'idle'}`);
+ return createElement(
+ 'div',
+ { 'data-testid': 'state' },
+ `${state.data?.commitOid ?? 'null'}|${state.loading ? 'loading' : 'idle'}`,
+ );
}
-function SummaryProbe({ sessionId, deviceId = null }: { sessionId: string | null; deviceId?: string | null }) {
+function SummaryProbe({
+ sessionId,
+ deviceId = null,
+}: {
+ sessionId: string | null;
+ deviceId?: string | null;
+}) {
const state = useReviewDirtySummary(sessionId, deviceId);
- return createElement('div', { 'data-testid': 'state' }, `${state.data?.sessionId ?? 'null'}|${state.loading ? 'loading' : 'idle'}`);
+ return createElement(
+ 'div',
+ { 'data-testid': 'state' },
+ `${state.data?.sessionId ?? 'null'}|${state.loading ? 'loading' : 'idle'}`,
+ );
}
function FileDiffProbe({
@@ -35,7 +61,11 @@ function FileDiffProbe({
refreshVersion: number;
}) {
const state = useReviewFileDiff(sessionId, request, refreshVersion);
- return createElement('div', { 'data-testid': 'state' }, `${state.data?.diff?.path ?? 'null'}|${state.loading ? 'loading' : 'idle'}`);
+ return createElement(
+ 'div',
+ { 'data-testid': 'state' },
+ `${state.data?.diff?.path ?? 'null'}|${state.loading ? 'loading' : 'idle'}`,
+ );
}
function FileDiffsProbe({
@@ -46,7 +76,11 @@ function FileDiffsProbe({
requests: readonly ReviewFileDiffRequest[];
}) {
const state = useReviewFileDiffs(sessionId, requests);
- return createElement('div', { 'data-testid': 'state' }, `${state.data?.length ?? 0}|${state.loading ? 'loading' : 'idle'}`);
+ return createElement(
+ 'div',
+ { 'data-testid': 'state' },
+ `${state.data?.length ?? 0}|${state.loading ? 'loading' : 'idle'}`,
+ );
}
function commitDiffData(commitOid: string): ReviewCommitDiffData {
@@ -98,6 +132,128 @@ function fileDiffData(path: string): ReviewFileDiffData {
};
}
+function runningSnapshot(
+ sessionId: string,
+ isRunning: boolean,
+): ReadonlyMap<string, SessionStatusInfo> {
+ if (!isRunning) return new Map();
+ return new Map([
+ [
+ sessionId,
+ {
+ isRunning: true,
+ hasError: false,
+ hasPendingAskUser: false,
+ hasPendingPermission: false,
+ hasPendingPlanReview: false,
+ hasPendingPluginSetup: false,
+ },
+ ],
+ ]);
+}
+
+describe('subscribeReviewRefreshOnTurnEnd', () => {
+ it('ignores stream updates while running and refreshes once on the stopped edge', () => {
+ const sessionId = 'turn-end-refresh-session';
+ let isRunning = true;
+ let listener = () => {};
+ const onTurnEnd = vi.fn();
+ const unsubscribe = vi.fn();
+ const store = {
+ getRunningSnapshot: () => runningSnapshot(sessionId, isRunning),
+ subscribe: (_sessionId: string, nextListener: () => void) => {
+ listener = nextListener;
+ return unsubscribe;
+ },
+ };
+
+ const cancelPendingRefresh = vi.fn();
+ const cleanup = subscribeReviewRefreshOnTurnEnd(
+ sessionId,
+ { onTurnEnd, cancelPendingRefresh },
+ store,
+ );
+
+ listener();
+ listener();
+ expect(onTurnEnd).not.toHaveBeenCalled();
+
+ isRunning = false;
+ listener();
+ listener();
+ expect(onTurnEnd).toHaveBeenCalledTimes(1);
+
+ cleanup();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ expect(cancelPendingRefresh).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a pending stopped-edge refresh when the Agent resumes', () => {
+ vi.useFakeTimers();
+ const sessionId = 'continuation-refresh-session';
+ let isRunning = true;
+ let listener = () => {};
+ let timer: number | null = null;
+ const refresh = vi.fn();
+ const onTurnEnd = () => {
+ timer = window.setTimeout(refresh, 350);
+ };
+ const cancelPendingRefresh = vi.fn(() => {
+ if (timer === null) return;
+ window.clearTimeout(timer);
+ timer = null;
+ });
+ const store = {
+ getRunningSnapshot: () => runningSnapshot(sessionId, isRunning),
+ subscribe: (_sessionId: string, nextListener: () => void) => {
+ listener = nextListener;
+ return () => {};
+ },
+ };
+ const cleanup = subscribeReviewRefreshOnTurnEnd(
+ sessionId,
+ { onTurnEnd, cancelPendingRefresh },
+ store,
+ );
+
+ isRunning = false;
+ listener();
+ isRunning = true;
+ listener();
+ vi.advanceTimersByTime(350);
+
+ expect(cancelPendingRefresh).toHaveBeenCalledTimes(1);
+ expect(refresh).not.toHaveBeenCalled();
+
+ cleanup();
+ expect(cancelPendingRefresh).toHaveBeenCalledTimes(2);
+ vi.useRealTimers();
+ });
+
+ it('does not treat non-running message updates as a completed turn', () => {
+ const sessionId = 'idle-refresh-session';
+ let listener = () => {};
+ const onTurnEnd = vi.fn();
+ const store = {
+ getRunningSnapshot: () => runningSnapshot(sessionId, false),
+ subscribe: (_sessionId: string, nextListener: () => void) => {
+ listener = nextListener;
+ return () => {};
+ },
+ };
+
+ subscribeReviewRefreshOnTurnEnd(
+ sessionId,
+ { onTurnEnd, cancelPendingRefresh: () => {} },
+ store,
+ );
+ listener();
+ listener();
+
+ expect(onTurnEnd).not.toHaveBeenCalled();
+ });
+});
+
describe('useReviewGitState cache continuity', () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -116,7 +272,9 @@ describe('useReviewGitState cache continuity', () => {
gitReview: { commitDiff },
};
- const { rerender } = render(createElement(Probe, { sessionId: 'cache-continuity-session', oid: 'commit-a' }));
+ const { rerender } = render(
+ createElement(Probe, { sessionId: 'cache-continuity-session', oid: 'commit-a' }),
+ );
await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('commit-a|idle'));
rerender(createElement(Probe, { sessionId: 'cache-continuity-session', oid: 'commit-b' }));
@@ -140,18 +298,22 @@ describe('useReviewGitState cache continuity', () => {
},
};
- const { rerender } = render(createElement(SummaryProbe, {
- sessionId: 'shared-session',
- deviceId: 'device-a',
- }));
+ const { rerender } = render(
+ createElement(SummaryProbe, {
+ sessionId: 'shared-session',
+ deviceId: 'device-a',
+ }),
+ );
await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('null|loading'));
let oldRequestResolved = false;
await act(async () => {
- rerender(createElement(SummaryProbe, {
- sessionId: 'shared-session',
- deviceId: 'device-b',
- }));
+ rerender(
+ createElement(SummaryProbe, {
+ sessionId: 'shared-session',
+ deviceId: 'device-b',
+ }),
+ );
pendingOld.resolve({ ok: true, result: dirtySummary('shared-session') });
oldRequestResolved = true;
await pendingOld.promise;
@@ -178,19 +340,23 @@ describe('useReviewGitState cache continuity', () => {
ignoreWhitespace: false,
};
- const { rerender } = render(createElement(FileDiffProbe, {
- sessionId: 'file-diff-write-version-session',
- request,
- refreshVersion: 0,
- }));
+ const { rerender } = render(
+ createElement(FileDiffProbe, {
+ sessionId: 'file-diff-write-version-session',
+ request,
+ refreshVersion: 0,
+ }),
+ );
await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('src/a.ts|idle'));
expect(fileDiff).toHaveBeenCalledTimes(1);
- rerender(createElement(FileDiffProbe, {
- sessionId: 'file-diff-write-version-session',
- request,
- refreshVersion: 1,
- }));
+ rerender(
+ createElement(FileDiffProbe, {
+ sessionId: 'file-diff-write-version-session',
+ request,
+ refreshVersion: 1,
+ }),
+ );
await waitFor(() => expect(fileDiff).toHaveBeenCalledTimes(2));
expect(fileDiff).toHaveBeenLastCalledWith({
@@ -205,7 +371,9 @@ describe('useReviewGitState cache continuity', () => {
});
it('does not reload a file diff batch when request array identity changes without content changes', async () => {
- const fileDiff = vi.fn(async (payload: ReviewFileDiffRequest & { sessionId: string }) => fileDiffData(payload.path));
+ const fileDiff = vi.fn(async (payload: ReviewFileDiffRequest & { sessionId: string }) =>
+ fileDiffData(payload.path),
+ );
(window as unknown as { electronAPI: unknown }).electronAPI = {
gitReview: { fileDiff },
};
@@ -218,17 +386,21 @@ describe('useReviewGitState cache continuity', () => {
ignoreWhitespace: false,
};
- const { rerender } = render(createElement(FileDiffsProbe, {
- sessionId: 'file-diff-batch-session',
- requests: [{ ...request }],
- }));
+ const { rerender } = render(
+ createElement(FileDiffsProbe, {
+ sessionId: 'file-diff-batch-session',
+ requests: [{ ...request }],
+ }),
+ );
await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('1|idle'));
expect(fileDiff).toHaveBeenCalledTimes(1);
- rerender(createElement(FileDiffsProbe, {
- sessionId: 'file-diff-batch-session',
- requests: [{ ...request }],
- }));
+ rerender(
+ createElement(FileDiffsProbe, {
+ sessionId: 'file-diff-batch-session',
+ requests: [{ ...request }],
+ }),
+ );
await new Promise((resolve) => window.setTimeout(resolve, 0));
expect(fileDiff).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
index 07b1e80af6..4a20237372 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
@@ -7,10 +7,10 @@
import { useCallback, useMemo, useSyncExternalStore } from 'react';
-import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
+import { makerChatStore } from '@/lib/makerChatStore';
import { collectLastTurnPaths } from '../../lib/lastTurnChangedFiles';
-const EMPTY_MESSAGES: readonly ChatMessage[] = Object.freeze([]);
+const EMPTY_PATH_SNAPSHOT = '[]';
export {
absoluteToWorkdirRelative as absoluteToRepoRelative,
@@ -25,10 +25,14 @@ export function useLastTurnFilter(sessionId: string | null, repoRoot: string | n
},
[sessionId],
);
- const getSnapshot = useCallback((): readonly ChatMessage[] => {
- if (!sessionId) return EMPTY_MESSAGES;
- return makerChatStore.getSnapshot(sessionId).messages;
- }, [sessionId]);
- const messages = useSyncExternalStore(subscribe, getSnapshot);
- return useMemo(() => collectLastTurnPaths(messages, repoRoot), [messages, repoRoot]);
+ const getSnapshot = useCallback((): string => {
+ if (!sessionId) return EMPTY_PATH_SNAPSHOT;
+ const paths = collectLastTurnPaths(makerChatStore.getSnapshot(sessionId).messages, repoRoot);
+ return JSON.stringify([...paths].sort());
+ }, [repoRoot, sessionId]);
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot);
+ return useMemo(
+ () => new Set<string>(JSON.parse(snapshot) as string[]),
+ [snapshot],
+ );
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts
index e8e7f72947..8c83e35678 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts
@@ -1,8 +1,9 @@
/**
* Hooks for git-review read state.
*
- * Refresh triggers are explicit refresh, window focus, and makerChatStore
- * updates for the current session (debounced; covers turn-end changes).
+ * Refresh triggers are explicit refresh, window focus, and the current Agent
+ * turn ending. Ordinary stream updates must not repeatedly reload the whole
+ * Review tree while the Agent is still working.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
@@ -27,6 +28,36 @@ const REFRESH_DEBOUNCE_MS = 350;
const FILE_DIFF_BATCH_CONCURRENCY = 6;
const reviewLoadCache = new LruCache<string, unknown>(20);
+type ReviewTurnActivityStore = Pick<typeof makerChatStore, 'getRunningSnapshot' | 'subscribe'>;
+
+/**
+ * Subscribe to the current session's running -> stopped edge.
+ *
+ * The session store also publishes text, tool, usage, and other stream updates.
+ * Reloading the full Git diff for every quiet gap between those updates can
+ * rebuild thousands of Review nodes several times during one Agent turn.
+ */
+export function subscribeReviewRefreshOnTurnEnd(
+ sessionId: string,
+ callbacks: {
+ onTurnEnd: () => void;
+ cancelPendingRefresh: () => void;
+ },
+ store: ReviewTurnActivityStore = makerChatStore,
+): () => void {
+ let wasRunning = store.getRunningSnapshot().get(sessionId)?.isRunning === true;
+ const unsubscribe = store.subscribe(sessionId, () => {
+ const isRunning = store.getRunningSnapshot().get(sessionId)?.isRunning === true;
+ if (wasRunning && !isRunning) callbacks.onTurnEnd();
+ if (!wasRunning && isRunning) callbacks.cancelPendingRefresh();
+ wasRunning = isRunning;
+ });
+ return () => {
+ unsubscribe();
+ callbacks.cancelPendingRefresh();
+ };
+}
+
interface LoadState<T> {
data: T | null;
loading: boolean;
@@ -37,17 +68,27 @@ interface LoadState<T> {
setData: (data: T) => void;
}
-function useDebouncedCallback(cb: () => void, delayMs: number): () => void {
+type CancelableCallback = (() => void) & { cancel: () => void };
+
+function useDebouncedCallback(cb: () => void, delayMs: number): CancelableCallback {
const timerRef = useRef<number | null>(null);
const cbRef = useRef(cb);
cbRef.current = cb;
- return useCallback(() => {
+ const cancel = useCallback(() => {
+ if (timerRef.current === null) return;
+ window.clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }, []);
+ const debounced = useCallback(() => {
if (timerRef.current !== null) window.clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => {
timerRef.current = null;
cbRef.current();
}, delayMs);
}, [delayMs]);
+ const cancelable = debounced as CancelableCallback;
+ cancelable.cancel = cancel;
+ return cancelable;
}
async function mapWithConcurrency<T, R>(
@@ -72,7 +113,11 @@ function useGitReviewLoad<T>(
sessionId: string | null,
fetch: (sessionId: string) => Promise<T>,
logLabel: string,
- options: { cacheKey?: string | null; preserveWhenDisabled?: boolean; scopeKey?: string | null } = {},
+ options: {
+ cacheKey?: string | null;
+ preserveWhenDisabled?: boolean;
+ scopeKey?: string | null;
+ } = {},
): LoadState<T> {
const cacheKey = options.cacheKey ?? null;
const preserveWhenDisabled = options.preserveWhenDisabled ?? false;
@@ -80,7 +125,7 @@ function useGitReviewLoad<T>(
// oid / baseRef / whitespace 等查询参数,粒度比 scope 细。
const scopeKey = options.scopeKey ?? cacheKey;
const [data, setDataState] = useState<T | null>(() => {
- const cached = cacheKey ? reviewLoadCache.get(cacheKey) as T | undefined : undefined;
+ const cached = cacheKey ? (reviewLoadCache.get(cacheKey) as T | undefined) : undefined;
return cached ?? null;
});
const [loading, setLoading] = useState(false);
@@ -102,7 +147,7 @@ function useGitReviewLoad<T>(
const scopeChanged = paintedScopeKey !== scopeKey;
setPaintedScopeKey(scopeKey);
setPaintedCacheKey(cacheKey);
- const cached = cacheKey ? reviewLoadCache.get(cacheKey) as T | undefined : undefined;
+ const cached = cacheKey ? (reviewLoadCache.get(cacheKey) as T | undefined) : undefined;
if (scopeChanged) {
// 立即让旧 scope 的在途请求失效;不能等新 scope 的 load effect,旧请求可能
// 在 render 与 effect 之间完成并把 A 会话数据写回 B 会话。
@@ -117,10 +162,13 @@ function useGitReviewLoad<T>(
setErrorCode(null);
}
}
- const setData = useCallback((next: T) => {
- setDataState(next);
- if (cacheKey) reviewLoadCache.set(cacheKey, next);
- }, [cacheKey]);
+ const setData = useCallback(
+ (next: T) => {
+ setDataState(next);
+ if (cacheKey) reviewLoadCache.set(cacheKey, next);
+ },
+ [cacheKey],
+ );
const load = useCallback(() => {
if (!sessionId) {
@@ -162,7 +210,10 @@ function useGitReviewLoad<T>(
if (!sessionId) return;
const onFocus = () => debouncedLoad();
window.addEventListener('focus', onFocus);
- const unsubscribe = makerChatStore.subscribe(sessionId, debouncedLoad);
+ const unsubscribe = subscribeReviewRefreshOnTurnEnd(sessionId, {
+ onTurnEnd: debouncedLoad,
+ cancelPendingRefresh: debouncedLoad.cancel,
+ });
return () => {
window.removeEventListener('focus', onFocus);
unsubscribe();
@@ -177,17 +228,28 @@ export function useReviewGitState(
ignoreWhitespace = false,
deviceId: string | null = null,
): LoadState<ReviewData> {
- const fetchReviewData = useCallback((currentSessionId: string) =>
- gitReviewApiFor(deviceId).get({ sessionId: currentSessionId, ignoreWhitespace }), [deviceId, ignoreWhitespace]);
+ const fetchReviewData = useCallback(
+ (currentSessionId: string) =>
+ gitReviewApiFor(deviceId).get({ sessionId: currentSessionId, ignoreWhitespace }),
+ [deviceId, ignoreWhitespace],
+ );
return useGitReviewLoad(sessionId, fetchReviewData, 'git review load failed', {
- cacheKey: sessionId ? `${deviceId ?? 'local'}:worktree:${sessionId}:${ignoreWhitespace ? 'w' : 'plain'}` : null,
+ cacheKey: sessionId
+ ? `${deviceId ?? 'local'}:worktree:${sessionId}:${ignoreWhitespace ? 'w' : 'plain'}`
+ : null,
scopeKey: sessionId ? `${deviceId ?? 'local'}:${sessionId}` : null,
});
}
-export function useReviewDirtySummary(sessionId: string | null, deviceId: string | null = null): LoadState<ReviewDirtySummary> {
- const fetchReviewSummary = useCallback((currentSessionId: string) =>
- gitReviewApiFor(deviceId).summary({ sessionId: currentSessionId }), [deviceId]);
+export function useReviewDirtySummary(
+ sessionId: string | null,
+ deviceId: string | null = null,
+): LoadState<ReviewDirtySummary> {
+ const fetchReviewSummary = useCallback(
+ (currentSessionId: string) =>
+ gitReviewApiFor(deviceId).summary({ sessionId: currentSessionId }),
+ [deviceId],
+ );
return useGitReviewLoad(sessionId, fetchReviewSummary, 'git review summary failed', {
scopeKey: sessionId ? `${deviceId ?? 'local'}:${sessionId}` : null,
});
@@ -198,8 +260,11 @@ export function useReviewCommits(
baseRef: string | null,
deviceId: string | null = null,
): LoadState<ReviewCommitListData> {
- const fetchReviewCommits = useCallback((currentSessionId: string) =>
- gitReviewApiFor(deviceId).commits({ sessionId: currentSessionId, baseRef }), [baseRef, deviceId]);
+ const fetchReviewCommits = useCallback(
+ (currentSessionId: string) =>
+ gitReviewApiFor(deviceId).commits({ sessionId: currentSessionId, baseRef }),
+ [baseRef, deviceId],
+ );
return useGitReviewLoad(sessionId, fetchReviewCommits, 'git review commits failed', {
scopeKey: sessionId ? `${deviceId ?? 'local'}:${sessionId}` : null,
});
@@ -211,15 +276,30 @@ export function useReviewCommitDiff(
ignoreWhitespace = false,
deviceId: string | null = null,
): LoadState<ReviewCommitDiffData> {
- const fetchCommitDiff = useCallback((currentSessionId: string) => {
- if (!oid) return Promise.reject(new Error('commit oid is required'));
- return gitReviewApiFor(deviceId).commitDiff({ sessionId: currentSessionId, oid, ignoreWhitespace });
- }, [deviceId, ignoreWhitespace, oid]);
- return useGitReviewLoad(sessionId && oid ? sessionId : null, fetchCommitDiff, 'git review commit diff failed', {
- cacheKey: sessionId && oid ? `${deviceId ?? 'local'}:commit:${sessionId}:${oid}:${ignoreWhitespace ? 'w' : 'plain'}` : null,
- scopeKey: sessionId && oid ? `${deviceId ?? 'local'}:${sessionId}` : null,
- preserveWhenDisabled: true,
- });
+ const fetchCommitDiff = useCallback(
+ (currentSessionId: string) => {
+ if (!oid) return Promise.reject(new Error('commit oid is required'));
+ return gitReviewApiFor(deviceId).commitDiff({
+ sessionId: currentSessionId,
+ oid,
+ ignoreWhitespace,
+ });
+ },
+ [deviceId, ignoreWhitespace, oid],
+ );
+ return useGitReviewLoad(
+ sessionId && oid ? sessionId : null,
+ fetchCommitDiff,
+ 'git review commit diff failed',
+ {
+ cacheKey:
+ sessionId && oid
+ ? `${deviceId ?? 'local'}:commit:${sessionId}:${oid}:${ignoreWhitespace ? 'w' : 'plain'}`
+ : null,
+ scopeKey: sessionId && oid ? `${deviceId ?? 'local'}:${sessionId}` : null,
+ preserveWhenDisabled: true,
+ },
+ );
}
export function useReviewBranchDiff(
@@ -229,17 +309,27 @@ export function useReviewBranchDiff(
enabled = true,
deviceId: string | null = null,
): LoadState<ReviewBranchDiffData> {
- const fetchBranchDiff = useCallback((currentSessionId: string) =>
- gitReviewApiFor(deviceId).branchDiff({
- sessionId: currentSessionId,
- baseRef,
- ignoreWhitespace,
- }), [baseRef, deviceId, ignoreWhitespace]);
- return useGitReviewLoad(sessionId && enabled ? sessionId : null, fetchBranchDiff, 'git review branch diff failed', {
- cacheKey: sessionId ? `${deviceId ?? 'local'}:branch:${sessionId}:${baseRef ?? 'default'}:${ignoreWhitespace ? 'w' : 'plain'}` : null,
- scopeKey: sessionId ? `${deviceId ?? 'local'}:${sessionId}` : null,
- preserveWhenDisabled: true,
- });
+ const fetchBranchDiff = useCallback(
+ (currentSessionId: string) =>
+ gitReviewApiFor(deviceId).branchDiff({
+ sessionId: currentSessionId,
+ baseRef,
+ ignoreWhitespace,
+ }),
+ [baseRef, deviceId, ignoreWhitespace],
+ );
+ return useGitReviewLoad(
+ sessionId && enabled ? sessionId : null,
+ fetchBranchDiff,
+ 'git review branch diff failed',
+ {
+ cacheKey: sessionId
+ ? `${deviceId ?? 'local'}:branch:${sessionId}:${baseRef ?? 'default'}:${ignoreWhitespace ? 'w' : 'plain'}`
+ : null,
+ scopeKey: sessionId ? `${deviceId ?? 'local'}:${sessionId}` : null,
+ preserveWhenDisabled: true,
+ },
+ );
}
export function useReviewFileDiff(
@@ -254,26 +344,35 @@ export function useReviewFileDiff(
const commitOid = request?.commitOid ?? null;
const branchBaseRef = request?.branchBaseRef ?? null;
const ignoreWhitespace = request?.ignoreWhitespace === true;
- const fetchFileDiff = useCallback((currentSessionId: string) => {
- if (!source || !path) return Promise.reject(new Error('file diff request is required'));
- return gitReviewApiFor(deviceId).fileDiff({
- sessionId: currentSessionId,
- source,
- path,
- oldPath,
- commitOid,
- branchBaseRef,
- ignoreWhitespace,
- });
- }, [branchBaseRef, commitOid, deviceId, ignoreWhitespace, oldPath, path, refreshVersion, source]);
- const cacheKey = sessionId && source && path
- ? `${deviceId ?? 'local'}:file:${sessionId}:${source}:${commitOid ?? branchBaseRef ?? 'worktree'}:${oldPath ?? ''}:${path}:${ignoreWhitespace ? 'w' : 'plain'}:${refreshVersion}`
- : null;
- return useGitReviewLoad(sessionId && source && path ? sessionId : null, fetchFileDiff, 'git review file diff failed', {
- cacheKey,
- scopeKey: sessionId && source && path ? `${deviceId ?? 'local'}:${sessionId}` : null,
- preserveWhenDisabled: true,
- });
+ const fetchFileDiff = useCallback(
+ (currentSessionId: string) => {
+ if (!source || !path) return Promise.reject(new Error('file diff request is required'));
+ return gitReviewApiFor(deviceId).fileDiff({
+ sessionId: currentSessionId,
+ source,
+ path,
+ oldPath,
+ commitOid,
+ branchBaseRef,
+ ignoreWhitespace,
+ });
+ },
+ [branchBaseRef, commitOid, deviceId, ignoreWhitespace, oldPath, path, refreshVersion, source],
+ );
+ const cacheKey =
+ sessionId && source && path
+ ? `${deviceId ?? 'local'}:file:${sessionId}:${source}:${commitOid ?? branchBaseRef ?? 'worktree'}:${oldPath ?? ''}:${path}:${ignoreWhitespace ? 'w' : 'plain'}:${refreshVersion}`
+ : null;
+ return useGitReviewLoad(
+ sessionId && source && path ? sessionId : null,
+ fetchFileDiff,
+ 'git review file diff failed',
+ {
+ cacheKey,
+ scopeKey: sessionId && source && path ? `${deviceId ?? 'local'}:${sessionId}` : null,
+ preserveWhenDisabled: true,
+ },
+ );
}
export function useReviewFileDiffs(
@@ -281,34 +380,42 @@ export function useReviewFileDiffs(
requests: readonly ReviewFileDiffRequest[],
deviceId: string | null = null,
): LoadState<ReviewFileDiffData[]> {
- const requestKey = requests.length > 0
- ? JSON.stringify(requests.map((request) => ({
- source: request.source,
- path: request.path,
- oldPath: request.oldPath ?? null,
- commitOid: request.commitOid ?? null,
- branchBaseRef: request.branchBaseRef ?? null,
- ignoreWhitespace: request.ignoreWhitespace === true,
- })))
- : null;
+ const requestKey =
+ requests.length > 0
+ ? JSON.stringify(
+ requests.map((request) => ({
+ source: request.source,
+ path: request.path,
+ oldPath: request.oldPath ?? null,
+ commitOid: request.commitOid ?? null,
+ branchBaseRef: request.branchBaseRef ?? null,
+ ignoreWhitespace: request.ignoreWhitespace === true,
+ })),
+ )
+ : null;
// React exhaustive-deps note: requestKey encodes request contents; array identity changes alone should not reload the batch.
- const fetchFileDiffs = useCallback((currentSessionId: string) =>
- mapWithConcurrency(requests, FILE_DIFF_BATCH_CONCURRENCY, (request) =>
- gitReviewApiFor(deviceId).fileDiff({
- sessionId: currentSessionId,
- source: request.source,
- path: request.path,
- oldPath: request.oldPath ?? null,
- commitOid: request.commitOid ?? null,
- branchBaseRef: request.branchBaseRef ?? null,
- ignoreWhitespace: request.ignoreWhitespace === true,
- })), [deviceId, requestKey]);
+ const fetchFileDiffs = useCallback(
+ (currentSessionId: string) =>
+ mapWithConcurrency(requests, FILE_DIFF_BATCH_CONCURRENCY, (request) =>
+ gitReviewApiFor(deviceId).fileDiff({
+ sessionId: currentSessionId,
+ source: request.source,
+ path: request.path,
+ oldPath: request.oldPath ?? null,
+ commitOid: request.commitOid ?? null,
+ branchBaseRef: request.branchBaseRef ?? null,
+ ignoreWhitespace: request.ignoreWhitespace === true,
+ }),
+ ),
+ [deviceId, requestKey],
+ );
return useGitReviewLoad(
sessionId && requestKey ? sessionId : null,
fetchFileDiffs,
'git review file diff batch failed',
{
- cacheKey: sessionId && requestKey ? `${deviceId ?? 'local'}:files:${sessionId}:${requestKey}` : null,
+ cacheKey:
+ sessionId && requestKey ? `${deviceId ?? 'local'}:files:${sessionId}:${requestKey}` : null,
scopeKey: sessionId && requestKey ? `${deviceId ?? 'local'}:${sessionId}` : null,
preserveWhenDisabled: false,
},