Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): persist review panel state
DavidShen41e8afbd15d5
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openTurnReview.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openTurnReview.test.tsindex 087f446232..ca004637ae 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openTurnReview.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openTurnReview.test.ts@@ -32,7 +32,7 @@ describe('openTurnReview', () => {mocks.ensureHydrated.mockResolvedValue(undefined);mocks.patchTabState.mockImplementation(async (_sessionId: string, _tabId: string, update: (current: unknown) => unknown) =>- update({ collapsedPaths: ['keep.ts'], turnTarget: { legacy: true } }),+ update({ diffsExpanded: false, turnTarget: { legacy: true } }),);});@@ -49,13 +49,18 @@ describe('openTurnReview', () => {const update = mocks.patchTabState.mock.calls[0]?.[2] as (current: unknown,) => Record<string, unknown>;- expect(update({ collapsedPaths: ['keep.ts'], turnTarget: { legacy: true } })).toEqual({- collapsedPaths: ['keep.ts'],+ expect(update({ diffsExpanded: false, turnTarget: { legacy: true } })).toEqual({+ diffsExpanded: false,descriptor: {kind: 'turn-set',changeSetIds: ['set-1'],targetSessionId: 'worker-session',},+ messageSnapshot: {+ kind: 'turn-set',+ changeSetIds: ['set-1'],+ targetSessionId: 'worker-session',+ },jumpTarget: {diffId: 'unstaged:src/a.ts',path: 'src/a.ts',diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.tsindex 7c30d22cb0..6406c1cf43 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts@@ -42,16 +42,18 @@ export async function openTurnReview(await patchTabState(hostSessionId, tab.id, (current) => {const preserved =current && typeof current === 'object' ? { ...(current as Record<string, unknown>) } : {};+ const messageSnapshot = {+ kind: 'turn-set' as const,+ changeSetIds,+ // 目标会话与宿主桶不同(跨会话审查 worker 的轮次)时,review 插件按它取数。+ targetSessionId: sessionId,+ };delete preserved.turnTarget;delete preserved.branchBaseRef;return {...preserved,- descriptor: {- kind: 'turn-set',- changeSetIds,- // 目标会话与宿主桶不同(跨会话审查 worker 的轮次)时,review 插件按它取数。- targetSessionId: sessionId,- },+ descriptor: messageSnapshot,+ messageSnapshot,jumpTarget: {diffId: opts.selectedDiffId ?? null,path: opts.selectedPath ?? null,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.tsxindex 9308f6569d..e9a4b8611c 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@@ -89,6 +89,7 @@ import { buildCappedDiffData } from '../../../../../shared/gitReviewCapped';import { capabilitiesFor, type ReviewSourceDescriptor } from '../../../../../shared/reviewSource';import type { TabKindHostContext } from '../../types';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';@@ -97,7 +98,7 @@ import {filterReviewFileJumpResults,findReviewFileTreeFileIndex,flattenReviewFileTree,- getReviewDiffExpansionToggle,+ getReviewDiffExpansionAction,getReviewFileTreeVisibility,isReviewFileTreeScrollKey,moveReviewFileJumpSelection,@@ -243,9 +244,14 @@ export function filterWhitespaceHiddenDiffs(export function getExpandedDiffSet(diffs: readonly Pick<FileDiff, 'id'>[],- collapsedPaths: ReadonlySet<string>,+ diffsExpanded: boolean,+ expansionOverrides: ReadonlyMap<string, boolean>,): Set<string> {- return new Set(diffs.map((diff) => diff.id).filter((id) => !collapsedPaths.has(id)));+ return new Set(+ diffs+ .map((diff) => diff.id)+ .filter((id) => (expansionOverrides.get(id) ?? diffsExpanded) === true),+ );}export function summaryEntryToPlaceholderDiff(entry: ReviewDiffSummaryEntry): FileDiff {@@ -428,6 +434,8 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const sessionId = ctx.sessionId || null;const hideWhitespace = state.hideWhitespace ?? false;const descriptor = state.descriptor;+ const messageSnapshot =+ state.messageSnapshot ?? (descriptor.kind === 'turn-set' ? descriptor : null);const source: ReviewSource | 'turn' = descriptor.kind === 'turn-set' ? 'turn' : descriptor.kind;const branchBaseRef = descriptor.kind === 'branch' ? descriptor.baseRef : null;const selectedCommitOid = descriptor.kind === 'commit' ? descriptor.commitOid : null;@@ -461,6 +469,9 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {},[setDescriptor],);+ const selectMessageSnapshot = useCallback(() => {+ if (messageSnapshot) setDescriptor(messageSnapshot);+ }, [messageSnapshot, setDescriptor]);const sourceState = useReviewSource(descriptor, sessionId, {hideWhitespace,deviceLinkDeviceId,@@ -503,7 +514,18 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const wordWrap = state.wordWrap ?? false;const wordDiff = state.wordDiff ?? false;const richMarkdownPreview = state.richMarkdownPreview ?? true;- const collapsedSet = useMemo(() => new Set(state.collapsedPaths ?? []), [state.collapsedPaths]);+ const persistedDiffsExpanded = state.diffsExpanded ?? true;+ const diffsExpanded = getReviewDiffsExpanded(sessionId ?? '', persistedDiffsExpanded);+ const [diffExpansionOverrides, setDiffExpansionOverrides] = useState<Map<string, boolean>>(+ () => new Map(),+ );+ useEffect(() => {+ if (!sessionId) return;+ setReviewDiffsExpanded(sessionId, diffsExpanded);+ if (diffsExpanded !== persistedDiffsExpanded) {+ ctx.patchState({ diffsExpanded });+ }+ }, [ctx, diffsExpanded, persistedDiffsExpanded, sessionId]);const rawUnstaged = data?.diffs.unstaged ?? [];const rawStaged = data?.diffs.staged ?? [];const worktreeCapped = data?.diffs.capped ?? null;@@ -533,8 +555,8 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {);const visibleDiffs = currentCapped ? cappedSummaryDiffs : sourceState.diffs;const expandedSet = useMemo(- () => getExpandedDiffSet(visibleDiffs, collapsedSet),- [collapsedSet, visibleDiffs],+ () => getExpandedDiffSet(visibleDiffs, diffsExpanded, diffExpansionOverrides),+ [diffExpansionOverrides, diffsExpanded, visibleDiffs],);const entryJumpDiff = state.jumpTarget?.diffId? visibleDiffs.find((diff) => diff.id === state.jumpTarget?.diffId)@@ -581,13 +603,13 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const lastTurnHydrating =source === 'last-turn' && sourceState.loading && sourceState.diffs.length === 0;const lastTurnHydrationError = source === 'last-turn' ? sourceState.error : null;- const expansionToggle = useMemo(+ const expansionAction = useMemo(() =>- getReviewDiffExpansionToggle(+ getReviewDiffExpansionAction(expansionDiffs.map((diff) => diff.id),- collapsedSet,+ diffsExpanded,),- [collapsedSet, expansionDiffs],+ [diffsExpanded, expansionDiffs],);const gitApplyAvailability = useMemo(() => getGitApplyCopyAvailability(visibleDiffs, hideWhitespace, platform),@@ -1037,12 +1059,15 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const togglePath = useCallback((id: string) => {- const next = new Set(collapsedSet);- if (expandedSet.has(id)) next.add(id);- else next.delete(id);- ctx.patchState({ collapsedPaths: Array.from(next) });+ setDiffExpansionOverrides((current) => {+ const next = new Map(current);+ const nextExpanded = !(next.get(id) ?? diffsExpanded);+ if (nextExpanded === diffsExpanded) next.delete(id);+ else next.set(id, nextExpanded);+ return next;+ });},- [collapsedSet, ctx, expandedSet],+ [diffsExpanded],);const setDiffViewMode = useCallback((mode: DiffViewMode) => {@@ -1098,18 +1123,19 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const selectCappedFile = useCallback((diff: FileDiff) => {setSelectedCappedFileId(diff.id);- if (collapsedSet.has(diff.id)) {- const next = new Set(collapsedSet);- next.delete(diff.id);- ctx.patchState({ collapsedPaths: Array.from(next) });+ if (!expandedSet.has(diff.id)) {+ setDiffExpansionOverrides((current) => new Map(current).set(diff.id, true));}},- [collapsedSet, ctx],+ [expandedSet],);const toggleAllDiffs = useCallback(() => {- if (expansionToggle.action === 'disabled') return;- ctx.patchState({ collapsedPaths: expansionToggle.nextCollapsedPaths });- }, [ctx, expansionToggle]);+ if (expansionAction === 'disabled') return;+ const nextDiffsExpanded = expansionAction === 'expand';+ setDiffExpansionOverrides(new Map());+ if (sessionId) setReviewDiffsExpanded(sessionId, nextDiffsExpanded);+ ctx.patchState({ diffsExpanded: nextDiffsExpanded });+ }, [ctx, expansionAction, sessionId]);const copyGitApplyCommand = useCallback(() => {const availability = getGitApplyCopyAvailability(visibleDiffs, hideWhitespace, platform);if (!availability.canCopy) return;@@ -1124,12 +1150,10 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {const nextId = getNextCappedFileSelection(selectedCappedFileId, cappedSummaryDiffs);if (nextId === selectedCappedFileId) return;setSelectedCappedFileId(nextId);- if (nextId && collapsedSet.has(nextId)) {- const next = new Set(collapsedSet);- next.delete(nextId);- ctx.patchState({ collapsedPaths: Array.from(next) });+ if (nextId && !expandedSet.has(nextId)) {+ setDiffExpansionOverrides((current) => new Map(current).set(nextId, true));}- }, [cappedSummaryDiffs, collapsedSet, ctx, currentCapped, selectedCappedFileId]);+ }, [cappedSummaryDiffs, currentCapped, expandedSet, selectedCappedFileId]);useEffect(() => {// 切 source 后 DiffList 重挂载、nonce 去重 ref 归零;残留的@@ -1267,6 +1291,7 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {><SourceDropdownsource={source}+ messageSnapshotAvailable={messageSnapshot !== null}counts={{unstaged: sourceUnstagedCount,staged: sourceStagedCount,@@ -1285,6 +1310,7 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {: t('rightSidebar.review.turn.crossSessionSwitchDisabled')}onChange={setSource}+ onSelectMessageSnapshot={selectMessageSnapshot}onSelectCommit={selectCommitSource}onRefreshCommits={commitsState.refresh}/>@@ -1325,7 +1351,7 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {toolbarShowSecondaryActions? null: {- action: expansionToggle.action,+ action: expansionAction,onToggle: toggleAllDiffs,}}@@ -1351,10 +1377,7 @@ export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {/>{toolbarShowSecondaryActions && (<>- <DiffExpansionToggleButton- action={expansionToggle.action}- onToggle={toggleAllDiffs}- />+ <DiffExpansionToggleButton action={expansionAction} onToggle={toggleAllDiffs} /><FileTreeToggleButtonpreferenceVisible={fileTreeVisible}temporarilyHidden={toolbarFileTreeVisibility.temporarilyHidden}@@ -2495,6 +2518,7 @@ function FileTreeMenuItem({export function SourceDropdown({source,+ messageSnapshotAvailable = false,counts,commits,commitsLoading,@@ -2504,11 +2528,14 @@ export function SourceDropdown({layout = 'wide',disabledReason,onChange,+ onSelectMessageSnapshot,onSelectCommit,onRefreshCommits,}: {/** `'turn'` is the selected label for a persisted turn-set descriptor. */source: ReviewSource | 'turn';+ /** Whether the exact message snapshot remains available after selecting a Git source. */+ messageSnapshotAvailable?: boolean;counts: { unstaged?: number; staged?: number; branch?: number; lastTurn?: number };commits?: ReviewCommit[];commitsLoading?: boolean;@@ -2518,15 +2545,17 @@ export function SourceDropdown({layout?: ReviewToolbarLayout;disabledReason?: string;onChange: (source: ReviewSource) => void;+ onSelectMessageSnapshot?: () => void;onSelectCommit?: (oid: string) => void;onRefreshCommits?: () => void;}) {const { t } = useTranslation();const [open, setOpen] = useState(false);- // 轮次项只在轮次审查态存在(进入它的唯一入口是聊天流的变更卡片);- // 切走即整体替换 descriptor,不提供"切回轮次"的常驻项。+ // 消息快照独立于当前来源保存;切到 Git 来源后仍可精确返回原消息的变更。const turnOption: SourceDropdownOption | null =- source === 'turn' ? { source: 'turn', label: t('rightSidebar.review.turn.title') } : null;+ source === 'turn' || messageSnapshotAvailable+ ? { source: 'turn', label: t('rightSidebar.review.turn.title') }+ : null;const options: SourceDropdownOption[] = [{ source: 'unstaged', label: t('rightSidebar.review.source.unstaged'), count: counts.unstaged },{ source: 'staged', label: t('rightSidebar.review.source.staged'), count: counts.staged },@@ -2535,7 +2564,10 @@ export function SourceDropdown({{ source: 'last-turn', label: t('rightSidebar.review.source.lastTurn') },];const directOptions = options.filter((option) => option.source !== 'commit');- const selected = turnOption ?? options.find((option) => option.source === source) ?? options[0];+ const selected =+ source === 'turn' && turnOption+ ? turnOption+ : (options.find((option) => option.source === source) ?? options[0]);const commitList = commits ?? [];const commitMenuLoaded = commitsLoaded ?? false;return (@@ -2572,7 +2604,14 @@ export function SourceDropdown({sideOffset={4}className="w-[var(--radix-dropdown-menu-trigger-width)] min-w-[12rem] rounded-[8px] border border-[var(--cmd-palette-border)] bg-[var(--cmd-palette-bg)] p-1 shadow-[var(--shadow-menu)]">- {turnOption && <SourceDropdownItem option={turnOption} active onChange={onChange} />}+ {turnOption && (+ <SourceDropdownItem+ option={turnOption}+ active={source === 'turn'}+ onChange={onChange}+ onSelectMessageSnapshot={onSelectMessageSnapshot}+ />+ )}{directOptions.slice(0, 2).map((option) => (<SourceDropdownItemkey={option.source}@@ -2705,16 +2744,21 @@ function SourceDropdownItem({option,active,onChange,+ onSelectMessageSnapshot,}: {option: SourceDropdownOption;active: boolean;onChange: (source: ReviewSource) => void;+ onSelectMessageSnapshot?: () => void;}) {return (<DropdownMenuItem- // 轮次伪选项已是选中态,点它只关菜单,不产生来源切换。onSelect={() => {- if (option.source !== 'turn') onChange(option.source);+ if (option.source === 'turn') {+ if (!active) onSelectMessageSnapshot?.();+ return;+ }+ onChange(option.source);}}className="flex h-8 items-center gap-2 rounded-[6px] px-2 text-12 text-[var(--text-primary)] focus:bg-[var(--cmd-palette-item-hover)]">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.tsindex 84eb088c39..f6249113d3 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@@ -177,16 +177,20 @@ describe('ReviewTabBody hunk action eligibility', () => {});describe('ReviewTabBody diff expansion state', () => {- it('expands every visible diff by default and removes collapsed ids only', () => {+ it('combines the persisted all-diff default with ephemeral per-file overrides', () => {const diffs = [diff('unstaged', 'a.ts'), diff('unstaged', 'b.ts')];- expect(Array.from(getExpandedDiffSet(diffs, new Set()))).toEqual([+ expect(Array.from(getExpandedDiffSet(diffs, true, new Map()))).toEqual(['unstaged:a.ts','unstaged:b.ts',]);- expect(Array.from(getExpandedDiffSet(diffs, new Set(['unstaged:b.ts'])))).toEqual([- 'unstaged:a.ts',- ]);+ expect(+ Array.from(getExpandedDiffSet(diffs, true, new Map([['unstaged:b.ts', false]]))),+ ).toEqual(['unstaged:a.ts']);+ expect(+ Array.from(getExpandedDiffSet(diffs, false, new Map([['unstaged:b.ts', true]]))),+ ).toEqual(['unstaged:b.ts']);+ expect(Array.from(getExpandedDiffSet(diffs, false, new Map()))).toEqual([]);});});@@ -314,25 +318,51 @@ describe('ReviewTabBody turn source dropdown', () => {expect(onChange).toHaveBeenCalledWith('unstaged');});- it('keeps the turn pseudo-item selection-only (no source change on click)', async () => {+ it('keeps the selected message snapshot item as a no-op', async () => {const onChange = vi.fn();+ const onSelectMessageSnapshot = vi.fn();render(createElement(SourceDropdown, {source: 'turn',counts: {},onChange,+ onSelectMessageSnapshot,+ }),+ );++ const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });+ fireEvent.keyDown(trigger, { key: 'Enter' });+ fireEvent.click(+ await screen.findByRole('menuitem', { name: 'rightSidebar.review.turn.title' }),+ );+ expect(onChange).not.toHaveBeenCalled();+ expect(onSelectMessageSnapshot).not.toHaveBeenCalled();+ });++ it('keeps the message snapshot available while a git source is active and restores it', async () => {+ const onChange = vi.fn();+ const onSelectMessageSnapshot = vi.fn();+ render(+ createElement(SourceDropdown, {+ source: 'unstaged',+ messageSnapshotAvailable: true,+ counts: { unstaged: 0, staged: 0, branch: 0, lastTurn: 0 },+ onChange,+ onSelectMessageSnapshot,}),);const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });+ expect(trigger.textContent).toBe('rightSidebar.review.source.unstaged');fireEvent.keyDown(trigger, { key: 'Enter' });fireEvent.click(await screen.findByRole('menuitem', { name: 'rightSidebar.review.turn.title' }),);+ expect(onSelectMessageSnapshot).toHaveBeenCalledTimes(1);expect(onChange).not.toHaveBeenCalled();});- it('does not offer the turn pseudo-item while a git source is active', async () => {+ it('does not offer a message snapshot for a normal review tab', async () => {render(createElement(SourceDropdown, {source: 'unstaged',diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/diffExpansionPreference.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/diffExpansionPreference.test.tsnew file mode 100644index 0000000000..6ecc29c3d3--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/diffExpansionPreference.test.ts@@ -0,0 +1,33 @@+import { beforeEach, describe, expect, it } from 'vitest';++import {+ getReviewDiffsExpanded,+ resetReviewDiffExpansionPreferencesForTests,+ seedReviewDiffsExpanded,+ setReviewDiffsExpanded,+} from '../diffExpansionPreference';++describe('review diff expansion preference', () => {+ beforeEach(() => {+ resetReviewDiffExpansionPreferencesForTests();+ });++ it('retains the first task state across review tab recreation until the user changes it', () => {+ seedReviewDiffsExpanded('session-a', false);+ seedReviewDiffsExpanded('session-a', true);+ expect(getReviewDiffsExpanded('session-a', true)).toBe(false);++ setReviewDiffsExpanded('session-a', true);+ expect(getReviewDiffsExpanded('session-a', false)).toBe(true);+ });++ it('keeps only the 20 most recently changed tasks', () => {+ for (let index = 0; index <= 20; index += 1) {+ setReviewDiffsExpanded(`session-${index}`, false);+ }++ expect(getReviewDiffsExpanded('session-0', true)).toBe(true);+ expect(getReviewDiffsExpanded('session-1', true)).toBe(false);+ expect(getReviewDiffsExpanded('session-20', true)).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/fileTree.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/fileTree.test.tsindex bdda9c2ff2..66916de028 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/fileTree.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/fileTree.test.ts@@ -7,7 +7,7 @@ import {filterReviewFileJumpResults,findReviewFileTreeFileIndex,flattenReviewFileTree,- getReviewDiffExpansionToggle,+ getReviewDiffExpansionAction,getReviewFileTreeVisibility,isReviewFileTreeScrollKey,moveReviewFileJumpSelection,@@ -62,11 +62,10 @@ describe('review file tree helpers', () => {});it('filters by path substring while preserving the matching directory chain', () => {- const { nodes, matchedDiffs } = buildFilteredReviewFileTree([- diff('src/app.ts'),- diff('src/components/Button.tsx'),- diff('docs/Button.md'),- ], 'components/button');+ const { nodes, matchedDiffs } = buildFilteredReviewFileTree(+ [diff('src/app.ts'), diff('src/components/Button.tsx'), diff('docs/Button.md')],+ 'components/button',+ );expect(matchedDiffs.map((item) => item.path)).toEqual(['src/components/Button.tsx']);const flat = flattenReviewFileTree(nodes, new Set());@@ -78,19 +77,14 @@ describe('review file tree helpers', () => {});it('returns an empty tree when no file matches the filter', () => {- const { nodes, matchedDiffs } = buildFilteredReviewFileTree([- diff('src/app.ts'),- ], 'missing');+ const { nodes, matchedDiffs } = buildFilteredReviewFileTree([diff('src/app.ts')], 'missing');expect(nodes).toEqual([]);expect(matchedDiffs).toEqual([]);});it('omits children below collapsed directories', () => {- const tree = buildReviewFileTree([- diff('src/app.ts'),- diff('src/components/Button.tsx'),- ]);+ const tree = buildReviewFileTree([diff('src/app.ts'), diff('src/components/Button.tsx')]);const flat = flattenReviewFileTree(tree, new Set(['dir:src']));expect(flat.map((item) => `${item.depth}:${item.node.type}:${item.node.name}`)).toEqual([@@ -99,126 +93,127 @@ describe('review file tree helpers', () => {});it('hides the sidebar until the user enables it and enough width is available', () => {- expect(shouldShowReviewFileTree({- userVisible: false,- containerWidth: 800,- fileCount: 2,- })).toBe(false);- expect(shouldShowReviewFileTree({- userVisible: true,- containerWidth: 500,- fileCount: 2,- })).toBe(false);- expect(shouldShowReviewFileTree({- userVisible: true,- containerWidth: 800,- fileCount: 0,- })).toBe(false);- expect(shouldShowReviewFileTree({- userVisible: true,- containerWidth: 800,- fileCount: 2,- })).toBe(true);+ expect(+ shouldShowReviewFileTree({+ userVisible: false,+ containerWidth: 800,+ fileCount: 2,+ }),+ ).toBe(false);+ expect(+ shouldShowReviewFileTree({+ userVisible: true,+ containerWidth: 500,+ fileCount: 2,+ }),+ ).toBe(false);+ expect(+ shouldShowReviewFileTree({+ userVisible: true,+ containerWidth: 800,+ fileCount: 0,+ }),+ ).toBe(false);+ expect(+ shouldShowReviewFileTree({+ userVisible: true,+ containerWidth: 800,+ fileCount: 2,+ }),+ ).toBe(true);});it('separates file tree user preference from effective narrow-width visibility', () => {- expect(getReviewFileTreeVisibility({- userVisible: true,- containerWidth: 500,- fileCount: 2,- })).toEqual({ effectiveVisible: false, temporarilyHidden: true });-- expect(getReviewFileTreeVisibility({- userVisible: true,- containerWidth: 620,- fileCount: 2,- })).toEqual({ effectiveVisible: true, temporarilyHidden: false });-- expect(getReviewFileTreeVisibility({- userVisible: false,- containerWidth: 500,- fileCount: 2,- })).toEqual({ effectiveVisible: false, temporarilyHidden: false });+ expect(+ getReviewFileTreeVisibility({+ userVisible: true,+ containerWidth: 500,+ fileCount: 2,+ }),+ ).toEqual({ effectiveVisible: false, temporarilyHidden: true });++ expect(+ getReviewFileTreeVisibility({+ userVisible: true,+ containerWidth: 620,+ fileCount: 2,+ }),+ ).toEqual({ effectiveVisible: true, temporarilyHidden: false });++ expect(+ getReviewFileTreeVisibility({+ userVisible: false,+ containerWidth: 500,+ fileCount: 2,+ }),+ ).toEqual({ effectiveVisible: false, temporarilyHidden: false });});it('disables expand-all toggle for an empty current source', () => {- expect(getReviewDiffExpansionToggle([], new Set(['unstaged:a.ts']))).toEqual({- action: 'disabled',- nextCollapsedPaths: ['unstaged:a.ts'],- });+ expect(getReviewDiffExpansionAction([], false)).toBe('disabled');});- it('collapses all current source diffs when the default state has every diff expanded', () => {- expect(getReviewDiffExpansionToggle(- ['unstaged:a.ts', 'unstaged:b.ts'],- new Set(['staged:collapsed.ts']),- )).toEqual({- action: 'collapse',- nextCollapsedPaths: ['staged:collapsed.ts', 'unstaged:a.ts', 'unstaged:b.ts'],- });+ it('collapses all diffs when their persisted default is expanded', () => {+ expect(getReviewDiffExpansionAction(['unstaged:a.ts', 'unstaged:b.ts'], true)).toBe('collapse');});- it('expands all current source diffs while preserving other collapsed ids', () => {- expect(getReviewDiffExpansionToggle(- ['unstaged:a.ts', 'unstaged:b.ts'],- new Set(['staged:collapsed.ts', 'unstaged:a.ts']),- )).toEqual({- action: 'expand',- nextCollapsedPaths: ['staged:collapsed.ts'],- });- });-- it('treats stale collapsed ids from other sources as unrelated to current toggle', () => {- expect(getReviewDiffExpansionToggle(- ['commit:a.ts'],- new Set(['unstaged:a.ts']),- )).toEqual({- action: 'collapse',- nextCollapsedPaths: ['unstaged:a.ts', 'commit:a.ts'],- });+ it('expands all diffs when their persisted default is collapsed', () => {+ expect(getReviewDiffExpansionAction(['unstaged:a.ts', 'unstaged:b.ts'], false)).toBe('expand');});it('keeps the pinned target active while programmatic scroll sync is suppressed', () => {- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.json',- candidateId: 'unstaged:case-123.json',- suppressed: true,- })).toEqual({ activeFileId: 'unstaged:case-124.json', releasePin: false });-- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.json',- candidateId: 'unstaged:case-125.json',- suppressed: false,- })).toEqual({ activeFileId: 'unstaged:case-125.json', releasePin: false });-- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.json',- candidateId: null,- suppressed: false,- })).toEqual({ activeFileId: 'unstaged:case-124.json', releasePin: false });+ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.json',+ candidateId: 'unstaged:case-123.json',+ suppressed: true,+ }),+ ).toEqual({ activeFileId: 'unstaged:case-124.json', releasePin: false });++ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.json',+ candidateId: 'unstaged:case-125.json',+ suppressed: false,+ }),+ ).toEqual({ activeFileId: 'unstaged:case-125.json', releasePin: false });++ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.json',+ candidateId: null,+ suppressed: false,+ }),+ ).toEqual({ activeFileId: 'unstaged:case-124.json', releasePin: false });});it('does not let late scroll sync overwrite a pinned jump target', () => {- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.ts',- candidateId: 'unstaged:case-104.ts',- suppressed: false,- pinnedTargetId: 'unstaged:case-124.ts',- })).toEqual({ activeFileId: 'unstaged:case-124.ts', releasePin: false });-- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.ts',- candidateId: 'unstaged:case-124.ts',- suppressed: true,- pinnedTargetId: 'unstaged:case-124.ts',- })).toEqual({ activeFileId: 'unstaged:case-124.ts', releasePin: true });-- expect(nextReviewFileTreeActiveIdFromScroll({- currentActiveFileId: 'unstaged:case-124.ts',- candidateId: 'unstaged:case-125.ts',- suppressed: false,- pinnedTargetId: null,- })).toEqual({ activeFileId: 'unstaged:case-125.ts', releasePin: false });+ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.ts',+ candidateId: 'unstaged:case-104.ts',+ suppressed: false,+ pinnedTargetId: 'unstaged:case-124.ts',+ }),+ ).toEqual({ activeFileId: 'unstaged:case-124.ts', releasePin: false });++ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.ts',+ candidateId: 'unstaged:case-124.ts',+ suppressed: true,+ pinnedTargetId: 'unstaged:case-124.ts',+ }),+ ).toEqual({ activeFileId: 'unstaged:case-124.ts', releasePin: true });++ expect(+ nextReviewFileTreeActiveIdFromScroll({+ currentActiveFileId: 'unstaged:case-124.ts',+ candidateId: 'unstaged:case-125.ts',+ suppressed: false,+ pinnedTargetId: null,+ }),+ ).toEqual({ activeFileId: 'unstaged:case-125.ts', releasePin: false });});it('recognizes keyboard scroll intent keys', () => {@@ -229,29 +224,37 @@ describe('review file tree helpers', () => {});it('retries precise jump scroll while the target row is not mounted', () => {- expect(nextReviewFileJumpPreciseScrollStep({- targetStillPinned: true,- rowMounted: false,- attemptsLeft: 3,- })).toEqual({ action: 'retry', nextAttemptsLeft: 2 });-- expect(nextReviewFileJumpPreciseScrollStep({- targetStillPinned: true,- rowMounted: true,- attemptsLeft: 3,- })).toEqual({ action: 'scroll', nextAttemptsLeft: 3 });-- expect(nextReviewFileJumpPreciseScrollStep({- targetStillPinned: false,- rowMounted: false,- attemptsLeft: 3,- })).toEqual({ action: 'stop', nextAttemptsLeft: 3 });-- expect(nextReviewFileJumpPreciseScrollStep({- targetStillPinned: true,- rowMounted: false,- attemptsLeft: 0,- })).toEqual({ action: 'stop', nextAttemptsLeft: 0 });+ expect(+ nextReviewFileJumpPreciseScrollStep({+ targetStillPinned: true,+ rowMounted: false,+ attemptsLeft: 3,+ }),+ ).toEqual({ action: 'retry', nextAttemptsLeft: 2 });++ expect(+ nextReviewFileJumpPreciseScrollStep({+ targetStillPinned: true,+ rowMounted: true,+ attemptsLeft: 3,+ }),+ ).toEqual({ action: 'scroll', nextAttemptsLeft: 3 });++ expect(+ nextReviewFileJumpPreciseScrollStep({+ targetStillPinned: false,+ rowMounted: false,+ attemptsLeft: 3,+ }),+ ).toEqual({ action: 'stop', nextAttemptsLeft: 3 });++ expect(+ nextReviewFileJumpPreciseScrollStep({+ targetStillPinned: true,+ rowMounted: false,+ attemptsLeft: 0,+ }),+ ).toEqual({ action: 'stop', nextAttemptsLeft: 0 });});it('resolves active file index in flattened tree and respects collapsed directories', () => {@@ -271,11 +274,11 @@ describe('review file tree helpers', () => {});it('filters jump results by path and reports overflow', () => {- const { results, overflowCount, totalMatches } = filterReviewFileJumpResults([- diff('src/components/Button.tsx'),- diff('src/components/Input.tsx'),- diff('README.md'),- ], 'COMPONENTS', 1);+ const { results, overflowCount, totalMatches } = filterReviewFileJumpResults(+ [diff('src/components/Button.tsx'), diff('src/components/Input.tsx'), diff('README.md')],+ 'COMPONENTS',+ 1,+ );expect(totalMatches).toBe(2);expect(overflowCount).toBe(1);diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.tsindex efe5ae7279..db2b428353 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/plugin.test.ts@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';let registry: typeof import('../../../registry');let pluginMod: typeof import('../index');+let expansionPreference: typeof import('../diffExpansionPreference');describe('review plugin', () => {beforeEach(async () => {@@ -21,6 +22,8 @@ describe('review plugin', () => {vi.resetModules();registry = await import('../../../registry');pluginMod = await import('../index');+ expansionPreference = await import('../diffExpansionPreference');+ expansionPreference.resetReviewDiffExpansionPreferencesForTests();});afterEach(() => {@@ -35,23 +38,23 @@ describe('review plugin', () => {expect(got?.menu.enabled).toBe(true);});- it('defaultState returns fresh collapsedPaths array per call', () => {+ it('retains the all-diff preference before the review tab is deleted', async () => {+ const p = registry.getTabKind('review')!;+ await p.onBeforeClose?.(+ { ...(p.defaultState() as object), diffsExpanded: false },+ { tabId: 'review-tab', sessionId: 'session-a' },+ );++ expect(expansionPreference.getReviewDiffsExpanded('session-a', true)).toBe(false);+ });++ it('defaultState expands all diffs and includes the persisted review preferences', () => {const p = registry.getTabKind('review')!;const a = p.defaultState() as {descriptor: { kind: string };+ messageSnapshot: unknown;jumpTarget: unknown;- collapsedPaths: string[];- diffViewMode: string;- fileTreeVisible: boolean;- wordWrap: boolean;- wordDiff: boolean;- hideWhitespace: boolean;- richMarkdownPreview: boolean;- };- const b = p.defaultState() as {- descriptor: { kind: string };- jumpTarget: unknown;- collapsedPaths: string[];+ diffsExpanded: boolean;diffViewMode: string;fileTreeVisible: boolean;wordWrap: boolean;@@ -60,25 +63,21 @@ describe('review plugin', () => {richMarkdownPreview: boolean;};expect(a.descriptor).toEqual({ kind: 'unstaged' });+ expect(a.messageSnapshot).toBeNull();expect(a.jumpTarget).toBeNull();- expect(a.collapsedPaths).toEqual([]);- expect(b.collapsedPaths).toEqual([]);+ expect(a.diffsExpanded).toBe(true);expect(a.diffViewMode).toBe('unified');expect(a.fileTreeVisible).toBe(false);expect(a.wordWrap).toBe(false);expect(a.wordDiff).toBe(false);expect(a.hideWhitespace).toBe(false);expect(a.richMarkdownPreview).toBe(true);- // 不要让多个 tab 共享同一个数组引用 → mutate a 不影响 b- a.collapsedPaths.push('whatever');- expect(b.collapsedPaths).toEqual([]);});- it('hydrateState recovers valid collapsedPaths and drops legacy expandedPaths', () => {+ it('hydrateState recovers the persisted all-diff expansion preference', () => {const p = registry.getTabKind('review')!;const s = p.hydrateState!({- expandedPaths: ['legacy.ts'],- collapsedPaths: ['a.ts', 'b/c.tsx'],+ diffsExpanded: false,diffViewMode: 'split',fileTreeVisible: true,wordWrap: true,@@ -88,7 +87,7 @@ describe('review plugin', () => {descriptor: { kind: 'branch', baseRef: 'main' },jumpTarget: { diffId: 'branch:main:a.ts', path: 'a.ts', nonce: 3 },}) as {- collapsedPaths: string[];+ diffsExpanded: boolean;diffViewMode: string;fileTreeVisible: boolean;wordWrap: boolean;@@ -98,7 +97,7 @@ describe('review plugin', () => {descriptor: { kind: string; baseRef?: string | null };jumpTarget: { diffId: string | null; path: string | null; nonce: number } | null;};- expect(s.collapsedPaths).toEqual(['a.ts', 'b/c.tsx']);+ expect(s.diffsExpanded).toBe(false);expect(s.diffViewMode).toBe('split');expect(s.fileTreeVisible).toBe(true);expect(s.wordWrap).toBe(true);@@ -138,6 +137,45 @@ describe('review plugin', () => {).toEqual({ kind: 'unstaged' });});+ it('hydrates an exact message snapshot independently from the active git source', () => {+ const p = registry.getTabKind('review')!;+ const state = p.hydrateState!({+ descriptor: { kind: 'unstaged' },+ messageSnapshot: {+ kind: 'turn-set',+ targetSessionId: 'worker-session',+ changeSetIds: ['set-1', 'set-2'],+ },+ }) as { descriptor: unknown; messageSnapshot: unknown };++ expect(state.descriptor).toEqual({ kind: 'unstaged' });+ expect(state.messageSnapshot).toEqual({+ kind: 'turn-set',+ targetSessionId: 'worker-session',+ changeSetIds: ['set-1', 'set-2'],+ });+ });++ it('fails closed when the persisted message snapshot is invalid or not a turn set', () => {+ const p = registry.getTabKind('review')!;+ expect(+ (+ p.hydrateState!({+ descriptor: { kind: 'unstaged' },+ messageSnapshot: { kind: 'turn-set', changeSetIds: [] },+ }) as { messageSnapshot: unknown }+ ).messageSnapshot,+ ).toBeNull();+ expect(+ (+ p.hydrateState!({+ descriptor: { kind: 'staged' },+ messageSnapshot: { kind: 'unstaged' },+ }) as { messageSnapshot: unknown }+ ).messageSnapshot,+ ).toBeNull();+ });+it('migrates the legacy turnTarget into descriptor and jumpTarget once', () => {const p = registry.getTabKind('review')!;const state = p.hydrateState!({@@ -148,13 +186,14 @@ describe('review plugin', () => {requestNonce: 9,targetSessionId: 'worker-session',},- }) as { descriptor: unknown; jumpTarget: unknown };+ }) as { descriptor: unknown; messageSnapshot: unknown; jumpTarget: unknown };expect(state.descriptor).toEqual({kind: 'turn-set',changeSetIds: ['set-1', 'set-2'],targetSessionId: 'worker-session',});+ expect(state.messageSnapshot).toEqual(state.descriptor);expect(state.jumpTarget).toEqual({diffId: 'unstaged:src/a.ts',path: 'src/a.ts',@@ -231,27 +270,18 @@ describe('review plugin', () => {);});- it('hydrateState falls back to empty when raw is null / wrong shape', () => {+ it('hydrateState defaults to expanded when raw is null or has the wrong shape', () => {const p = registry.getTabKind('review')!;- expect((p.hydrateState!(null) as { collapsedPaths: string[] }).collapsedPaths).toEqual([]);- expect((p.hydrateState!('garbage') as { collapsedPaths: string[] }).collapsedPaths).toEqual([]);- expect((p.hydrateState!({}) as { collapsedPaths: string[] }).collapsedPaths).toEqual([]);+ expect((p.hydrateState!(null) as { diffsExpanded: boolean }).diffsExpanded).toBe(true);+ expect((p.hydrateState!('garbage') as { diffsExpanded: boolean }).diffsExpanded).toBe(true);+ expect((p.hydrateState!({}) as { diffsExpanded: boolean }).diffsExpanded).toBe(true);expect(- (p.hydrateState!({ collapsedPaths: 'not-an-array' }) as { collapsedPaths: string[] })- .collapsedPaths,- ).toEqual([]);+ (p.hydrateState!({ diffsExpanded: 'yes' }) as { diffsExpanded: boolean }).diffsExpanded,+ ).toBe(true);expect(- (p.hydrateState!({ expandedPaths: ['legacy-expanded.ts'] }) as { collapsedPaths: string[] })- .collapsedPaths,- ).toEqual([]);- });-- it('hydrateState filters out non-string entries', () => {- const p = registry.getTabKind('review')!;- const s = p.hydrateState!({- collapsedPaths: ['ok.ts', 123, null, undefined, 'also.tsx'],- }) as { collapsedPaths: string[] };- expect(s.collapsedPaths).toEqual(['ok.ts', 'also.tsx']);+ (p.hydrateState!({ expandedPaths: ['legacy-expanded.ts'] }) as { diffsExpanded: boolean })+ .diffsExpanded,+ ).toBe(true);});// 引用 pluginMod 让 lint 满意 + 验证 module load 成功diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.tsnew file mode 100644index 0000000000..5a7aed22e7--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts@@ -0,0 +1,28 @@+/** Codex-style route memory: closing a Review tab must not reset its task-level default. */+const MAX_RETAINED_REVIEW_TASKS = 20;++const diffsExpandedBySession = new Map<string, boolean>();++export function getReviewDiffsExpanded(sessionId: string, fallback: boolean): boolean {+ return diffsExpandedBySession.get(sessionId) ?? fallback;+}++export function seedReviewDiffsExpanded(sessionId: string, expanded: boolean): void {+ if (!sessionId || diffsExpandedBySession.has(sessionId)) return;+ setReviewDiffsExpanded(sessionId, expanded);+}++export function setReviewDiffsExpanded(sessionId: string, expanded: boolean): void {+ if (!sessionId) return;+ diffsExpandedBySession.delete(sessionId);+ diffsExpandedBySession.set(sessionId, expanded);+ while (diffsExpandedBySession.size > MAX_RETAINED_REVIEW_TASKS) {+ const oldestSessionId = diffsExpandedBySession.keys().next().value;+ if (oldestSessionId === undefined) break;+ diffsExpandedBySession.delete(oldestSessionId);+ }+}++export function resetReviewDiffExpansionPreferencesForTests(): void {+ diffsExpandedBySession.clear();+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.tsindex ab89ac417e..8aae71bd0e 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts@@ -47,11 +47,6 @@ export interface ReviewFileJumpPreciseScrollStep {export type ReviewDiffExpansionToggleAction = 'expand' | 'collapse' | 'disabled';-export interface ReviewDiffExpansionToggle {- action: ReviewDiffExpansionToggleAction;- nextCollapsedPaths: string[];-}-export interface ReviewFileTreeVisibility {effectiveVisible: boolean;temporarilyHidden: boolean;@@ -234,13 +229,15 @@ export function moveReviewFileJumpSelection(}export function isReviewFileTreeScrollKey(key: string): boolean {- return key === 'ArrowDown' ||+ return (+ key === 'ArrowDown' ||key === 'ArrowUp' ||key === 'PageDown' ||key === 'PageUp' ||key === 'Home' ||key === 'End' ||- key === ' ';+ key === ' '+ );}export function nextReviewFileJumpPreciseScrollStep({@@ -258,28 +255,12 @@ export function nextReviewFileJumpPreciseScrollStep({return { action: 'stop', nextAttemptsLeft: 0 };}-export function getReviewDiffExpansionToggle(+export function getReviewDiffExpansionAction(diffIds: readonly string[],- collapsedPaths: ReadonlySet<string>,-): ReviewDiffExpansionToggle {- const currentIds = [...new Set(diffIds)];- if (currentIds.length === 0) {- return { action: 'disabled', nextCollapsedPaths: Array.from(collapsedPaths) };- }-- const allExpanded = currentIds.every((id) => !collapsedPaths.has(id));- if (allExpanded) {- return {- action: 'collapse',- nextCollapsedPaths: Array.from(new Set([...collapsedPaths, ...currentIds])),- };- }-- const currentIdSet = new Set(currentIds);- return {- action: 'expand',- nextCollapsedPaths: Array.from(collapsedPaths).filter((id) => !currentIdSet.has(id)),- };+ diffsExpanded: boolean,+): ReviewDiffExpansionToggleAction {+ if (diffIds.length === 0) return 'disabled';+ return diffsExpanded ? 'collapse' : 'expand';}function materializeDirectory(dir: MutableDirectory): ReviewFileTreeDirectoryNode {diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsxindex c9284dee69..02ee971305 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx@@ -2,7 +2,7 @@* review plugin —— RSB 内统一显示当前 Git 状态与消息级历史变更的常驻 tab。** 数据源由可持久化 descriptor 选择;Git 来源走 git-review IPC,历史来源读取- * 已记录的 turn change sets。plugin 自身持久化用户收起过哪些 diff id(`collapsedPaths`)、diff 模式、文件树显隐、+ * 已记录的 turn change sets。plugin 自身持久化全部 diff 的默认展开状态、diff 模式、文件树显隐、* diff 自动换行偏好、文字差异偏好、隐藏空白变更偏好、Markdown 富文本预览偏好与分支来源的基准分支。** 单例语义 —— 由 RightSidebarShell + AddTabDropdown 在调用层用@@ -26,18 +26,21 @@ import {import { registerTabKind } from '../../registry';import type { TabKindPlugin } from '../../types';import type { DiffViewMode } from './DiffViewer/PlainUnifiedDiff';+import { seedReviewDiffsExpanded } from './diffExpansionPreference';const ReviewTabBody = lazy(() =>import('./ReviewTabBody').then((module) => ({ default: module.ReviewTabBody })),);export interface ReviewState {- /** Persisted discriminated source; all review entry points write the same field. */+ /** 当前选中的审查来源。 */descriptor: ReviewSourceDescriptor;+ /** 最近一次从消息变更卡片进入时的精确快照,切换 Git 来源后仍可返回。 */+ messageSnapshot: Extract<ReviewSourceDescriptor, { kind: 'turn-set' }> | null;/** Optional one-shot positioning request supplied by a review entry point. */jumpTarget: ReviewJumpTarget | null;- /** 用户收起过哪些 diff id。空数组表示所有当前 diff 默认展开。 */- collapsedPaths: string[];+ /** 所有 diff 的持久化默认展开状态;单文件覆盖只保留在当前组件生命周期。 */+ diffsExpanded: boolean;/** diff 展示模式。写操作仍回到原始 unified DiffLine.index。 */diffViewMode: DiffViewMode;/** 右侧已修改文件树显隐。默认收起,用户选择通过 tab state 记住。 */@@ -54,8 +57,9 @@ export interface ReviewState {const DEFAULT_STATE: ReviewState = {descriptor: { kind: 'unstaged' },+ messageSnapshot: null,jumpTarget: null,- collapsedPaths: [],+ diffsExpanded: true,diffViewMode: 'unified',fileTreeVisible: false,wordWrap: false,@@ -87,13 +91,12 @@ const plugin: TabKindPlugin<ReviewState> = {TabPillTitle: ReviewTabPillTitle,TabPillIcon: ReviewTabPillIcon,TabBody: ReviewTabBody,- defaultState: () => ({ ...DEFAULT_STATE, collapsedPaths: [] }),+ defaultState: () => ({ ...DEFAULT_STATE }),hydrateState: (raw): ReviewState => {- if (!raw || typeof raw !== 'object') return { ...DEFAULT_STATE, collapsedPaths: [] };+ if (!raw || typeof raw !== 'object') return { ...DEFAULT_STATE };const obj = raw as Record<string, unknown>;- const collapsedPaths = Array.isArray(obj.collapsedPaths)- ? obj.collapsedPaths.filter((s): s is string => typeof s === 'string')- : [];+ const diffsExpanded =+ typeof obj.diffsExpanded === 'boolean' ? obj.diffsExpanded : DEFAULT_STATE.diffsExpanded;const diffViewMode = obj.diffViewMode === 'split' ? 'split' : 'unified';const fileTreeVisible =typeof obj.fileTreeVisible === 'boolean'@@ -110,6 +113,13 @@ const plugin: TabKindPlugin<ReviewState> = {const legacyTurnTarget = migrateLegacyTurnTarget(obj.turnTarget);const persistedDescriptor = parseReviewSourceDescriptor(obj.descriptor);const descriptor = persistedDescriptor ?? legacyTurnTarget?.descriptor ?? { kind: 'unstaged' };+ const persistedMessageSnapshot = parseReviewSourceDescriptor(obj.messageSnapshot);+ const messageSnapshot =+ persistedMessageSnapshot?.kind === 'turn-set'+ ? persistedMessageSnapshot+ : descriptor.kind === 'turn-set'+ ? descriptor+ : null;const jumpTarget =parseReviewJumpTarget(obj.jumpTarget) ??(!persistedDescriptor && descriptor.kind === 'turn-set'@@ -117,8 +127,9 @@ const plugin: TabKindPlugin<ReviewState> = {: null);return {descriptor,+ messageSnapshot,jumpTarget,- collapsedPaths,+ diffsExpanded,diffViewMode,fileTreeVisible,wordWrap,@@ -127,6 +138,9 @@ const plugin: TabKindPlugin<ReviewState> = {richMarkdownPreview,};},+ onBeforeClose: (state, { sessionId }) => {+ seedReviewDiffsExpanded(sessionId, state?.diffsExpanded ?? DEFAULT_STATE.diffsExpanded);+ },};registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);