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。

WIP: unify desktop review panel sources

DavidShenb9da1c52c0c5
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.ts
new file mode 100644
index 0000000000..087f446232
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openTurnReview.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ addOrFocusSingletonTab: vi.fn(),
+ ensureHydrated: vi.fn(),
+ patchTabState: vi.fn(),
+ routeSidebarCommand: vi.fn(),
+ requestRightSidebarVisibility: vi.fn(),
+}));
+
+vi.mock('../../store', () => ({
+ addOrFocusSingletonTab: mocks.addOrFocusSingletonTab,
+ ensureHydrated: mocks.ensureHydrated,
+ patchTabState: mocks.patchTabState,
+}));
+
+vi.mock('../detachedSidebarRouting', () => ({
+ routeSidebarCommand: mocks.routeSidebarCommand,
+}));
+
+vi.mock('../sidebarCommands', () => ({
+ requestRightSidebarVisibility: mocks.requestRightSidebarVisibility,
+}));
+
+import { openTurnReview } from '../openTurnReview';
+
+describe('openTurnReview', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.routeSidebarCommand.mockResolvedValue('attached');
+ mocks.addOrFocusSingletonTab.mockResolvedValue({ id: 'review-tab' });
+ mocks.ensureHydrated.mockResolvedValue(undefined);
+ mocks.patchTabState.mockImplementation(
+ async (_sessionId: string, _tabId: string, update: (current: unknown) => unknown) =>
+ update({ collapsedPaths: ['keep.ts'], turnTarget: { legacy: true } }),
+ );
+ });
+
+ it('writes a descriptor and independent jump target into the singleton review tab', async () => {
+ await openTurnReview('worker-session', ['set-1'], {
+ hostSessionId: 'lead-session',
+ selectedDiffId: 'unstaged:src/a.ts',
+ selectedPath: 'src/a.ts',
+ requestNonce: 12,
+ });
+
+ expect(mocks.ensureHydrated).toHaveBeenCalledWith('lead-session');
+ expect(mocks.addOrFocusSingletonTab).toHaveBeenCalledWith('lead-session', 'review', null);
+ 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'],
+ descriptor: {
+ kind: 'turn-set',
+ changeSetIds: ['set-1'],
+ targetSessionId: 'worker-session',
+ },
+ jumpTarget: {
+ diffId: 'unstaged:src/a.ts',
+ path: 'src/a.ts',
+ nonce: 12,
+ },
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts
index 64669990b8..7c30d22cb0 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts
@@ -1,8 +1,4 @@
-import {
- addOrFocusSingletonTab,
- ensureHydrated,
- patchTabState,
-} from '../store';
+import { addOrFocusSingletonTab, ensureHydrated, patchTabState } from '../store';
import { routeSidebarCommand } from './detachedSidebarRouting';
import { requestRightSidebarVisibility } from './sidebarCommands';
@@ -36,22 +32,32 @@ export async function openTurnReview(
};
const routeResult = await routeSidebarCommand(command);
if (routeResult !== 'attached') {
- if (routeResult === 'routed') requestRightSidebarVisibility('open', { sessionId: hostSessionId });
+ if (routeResult === 'routed')
+ requestRightSidebarVisibility('open', { sessionId: hostSessionId });
return;
}
await ensureHydrated(hostSessionId);
const tab = await addOrFocusSingletonTab(hostSessionId, 'review', null);
- await patchTabState(hostSessionId, tab.id, (current) => ({
- ...(current && typeof current === 'object' ? current as Record<string, unknown> : {}),
- turnTarget: {
- changeSetIds,
- selectedDiffId: opts.selectedDiffId ?? null,
- selectedPath: opts.selectedPath ?? null,
- requestNonce,
- // 目标会话与宿主桶不同(跨会话审查 worker 的轮次)时,review 插件按它取数。
- targetSessionId: sessionId,
- },
- }));
+ await patchTabState(hostSessionId, tab.id, (current) => {
+ const preserved =
+ current && typeof current === 'object' ? { ...(current as Record<string, unknown>) } : {};
+ delete preserved.turnTarget;
+ delete preserved.branchBaseRef;
+ return {
+ ...preserved,
+ descriptor: {
+ kind: 'turn-set',
+ changeSetIds,
+ // 目标会话与宿主桶不同(跨会话审查 worker 的轮次)时,review 插件按它取数。
+ targetSessionId: sessionId,
+ },
+ jumpTarget: {
+ diffId: opts.selectedDiffId ?? null,
+ path: opts.selectedPath ?? null,
+ nonce: requestNonce,
+ },
+ };
+ });
requestRightSidebarVisibility('open', { sessionId: hostSessionId });
}
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 1144b4ef44..9308f6569d 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
@@ -1,11 +1,20 @@
/**
- * ReviewTabBody — git-backed workspace review panel.
+ * ReviewTabBody — unified workspace and recorded-message review panel.
*
- * M1 is read-only: it shows git status/diff for the session worktree and uses
- * agent messages only as a Last turn filter.
+ * A persisted descriptor selects the data source. The toolbar remains shared;
+ * source capabilities decide which actions are available.
*/
-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react';
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type KeyboardEvent,
+ type ReactNode,
+} from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import {
AlertTriangle,
@@ -60,7 +69,6 @@ import { formatSidebarTime } from '@/features/cc-agent/lib/formatSidebarTime';
import { gitReviewApiFor, isReviewRemoteOversizeError } from '@/lib/gitReviewTransport';
import { makerChatStore } from '@/lib/makerChatStore';
-import type { TurnChangeSetDetail } from '../../../../../shared/turnChangeSet';
import { extractIpcError } from '@/utils/ipcError';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
@@ -78,6 +86,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { Tip } from '@/components/ui/tooltip';
import { toast } from '@/lib/toast';
import { buildCappedDiffData } from '../../../../../shared/gitReviewCapped';
+import { capabilitiesFor, type ReviewSourceDescriptor } from '../../../../../shared/reviewSource';
import type { TabKindHostContext } from '../../types';
import type { ReviewState } from './index';
import { PlainUnifiedDiff, type DiffViewMode } from './DiffViewer/PlainUnifiedDiff';
@@ -100,31 +109,14 @@ import {
} from './fileTree';
import { getGitApplyCopyAvailability } from './gitApplyCommand';
import { getRichMarkdownPreviewEligibility } from './markdownPreview';
-import { useLastTurnFilter } from './useLastTurnFilter';
-import { useReviewBranchDiff, useReviewCommitDiff, useReviewCommits, useReviewFileDiff, useReviewFileDiffs, useReviewGitState } from './useReviewGitState';
+import { REVIEW_TURN_LOCAL_ONLY_ERROR, useReviewSource } from './useReviewSource';
+import { useReviewCommits, useReviewFileDiff } from './useReviewGitState';
interface ReviewTabBodyProps {
state: ReviewState;
ctx: TabKindHostContext;
}
-/**
- * source / selectedCommitOid 由外层 ReviewTabBody 持有并下发:轮次视图与
- * Git 视图共用同一个来源状态机,从轮次视图的来源下拉切走时目标 source
- * 要在 Git 视图挂载前就位(对齐 Codex 的单 source + turnSelection 模型)。
- */
-interface GitReviewBodyProps extends ReviewTabBodyProps {
- source: ReviewSource;
- setSource: (source: ReviewSource) => void;
- selectedCommitOid: string | null;
- setSelectedCommitOid: (oid: string | null) => void;
-}
-
-interface TurnReviewBodyProps extends ReviewTabBodyProps {
- setSource: (source: ReviewSource) => void;
- setSelectedCommitOid: (oid: string | null) => void;
-}
-
type ReviewToggleAction = Extract<ReviewStageAction, 'stage' | 'unstage'>;
type RevealActionScope = 'file' | 'section';
type ReviewToolbarLayout = 'wide' | 'compact' | 'minimal';
@@ -137,7 +129,8 @@ interface ReviewFileJumpRequest {
type LoadImagePreview = (diff: FileDiff) => Promise<ReviewImagePreviewData>;
type LoadMarkdownPreview = (diff: FileDiff) => Promise<ReviewMarkdownPreviewData>;
-const SECTION_ACTION_REVEAL_CLASS = 'invisible opacity-0 transition-opacity group-hover/section:visible group-hover/section:opacity-100 group-focus-within/section:visible group-focus-within/section:opacity-100';
+const SECTION_ACTION_REVEAL_CLASS =
+ 'invisible opacity-0 transition-opacity group-hover/section:visible group-hover/section:opacity-100 group-focus-within/section:visible group-focus-within/section:opacity-100';
// 断点按四语言最长文案(ja/ko 明显长于 zh/en)和 A/B 后 900px 窗口的
// 240px 实际 RSB 宽校准:240px 只能容纳 source + 统计 + 主操作 / 跳转 / More
@@ -159,20 +152,26 @@ export function getBatchActionLayout(containerWidth: number): BatchActionLayout
return containerWidth <= REVIEW_BATCH_ICON_ONLY_MAX_WIDTH_PX ? 'icon-only' : 'full';
}
-export function shouldShowBranchBaseLabel(rowWidth: number, hasBranchBaseControl: boolean): boolean {
- return hasBranchBaseControl && Number.isFinite(rowWidth) && rowWidth >= REVIEW_BRANCH_BASE_LABEL_MIN_WIDTH_PX;
+export function shouldShowBranchBaseLabel(
+ rowWidth: number,
+ hasBranchBaseControl: boolean,
+): boolean {
+ return (
+ hasBranchBaseControl &&
+ Number.isFinite(rowWidth) &&
+ rowWidth >= REVIEW_BRANCH_BASE_LABEL_MIN_WIDTH_PX
+ );
}
-export function shouldOfferReviewOpenFile(remoteHostId: string | null, deviceLinkDeviceId: string | null): boolean {
+export function shouldOfferReviewOpenFile(
+ remoteHostId: string | null,
+ deviceLinkDeviceId: string | null,
+): boolean {
return remoteHostId === null && deviceLinkDeviceId === null;
}
export type ReviewCommitActionDisabledReason =
- | 'no-message'
- | 'write-disabled'
- | 'no-changes'
- | 'no-staged'
- | null;
+ 'no-message' | 'write-disabled' | 'no-changes' | 'no-staged' | null;
export function getReviewCommitActionDisabledReason({
message,
@@ -208,7 +207,10 @@ export function getReviewCommitDropdownCompletionEffect(result: ReviewCommitRunR
};
}
-export function refreshBranchDiffAfterCommit(source: ReviewSource, refreshBranchDiff: () => void): void {
+export function refreshBranchDiffAfterCommit(
+ source: ReviewSource,
+ refreshBranchDiff: () => void,
+): void {
if (source === 'branch') refreshBranchDiff();
}
@@ -222,11 +224,19 @@ export function canUsePatchBasedReviewActions(hideWhitespace: boolean): boolean
return typeof hideWhitespace === 'boolean';
}
-export function shouldHideWhitespaceOnlyDiff(diff: Pick<FileDiff, 'kind' | 'status' | 'hunks'>, hideWhitespace: boolean): boolean {
- return hideWhitespace && diff.kind === 'text' && diff.status === 'modified' && diff.hunks.length === 0;
+export function shouldHideWhitespaceOnlyDiff(
+ diff: Pick<FileDiff, 'kind' | 'status' | 'hunks'>,
+ hideWhitespace: boolean,
+): boolean {
+ return (
+ hideWhitespace && diff.kind === 'text' && diff.status === 'modified' && diff.hunks.length === 0
+ );
}
-export function filterWhitespaceHiddenDiffs(diffs: readonly FileDiff[], hideWhitespace: boolean): FileDiff[] {
+export function filterWhitespaceHiddenDiffs(
+ diffs: readonly FileDiff[],
+ hideWhitespace: boolean,
+): FileDiff[] {
if (!hideWhitespace) return Array.from(diffs);
return diffs.filter((diff) => !shouldHideWhitespaceOnlyDiff(diff, true));
}
@@ -278,23 +288,26 @@ export function fileDiffToSummaryEntry(diff: FileDiff): ReviewDiffSummaryEntry {
}
export function getLastTurnCappedSummaryEntries(
- worktreeCapped: { staged: ReviewCappedDiffData | null; unstaged: ReviewCappedDiffData | null } | null | undefined,
+ worktreeCapped:
+ | { staged: ReviewCappedDiffData | null; unstaged: ReviewCappedDiffData | null }
+ | null
+ | undefined,
lastTurnPaths: ReadonlySet<string>,
): ReviewDiffSummaryEntry[] {
return [
...(worktreeCapped?.unstaged?.files ?? []),
...(worktreeCapped?.staged?.files ?? []),
- ].filter((entry) => lastTurnPaths.has(entry.path) || (entry.oldPath !== null && lastTurnPaths.has(entry.oldPath)));
+ ].filter(
+ (entry) =>
+ lastTurnPaths.has(entry.path) || (entry.oldPath !== null && lastTurnPaths.has(entry.oldPath)),
+ );
}
export function buildLastTurnCappedData(
availableDiffs: readonly FileDiff[],
cappedEntries: readonly ReviewDiffSummaryEntry[],
): ReviewCappedDiffData | null {
- return buildCappedDiffData([
- ...availableDiffs.map(fileDiffToSummaryEntry),
- ...cappedEntries,
- ]);
+ return buildCappedDiffData([...availableDiffs.map(fileDiffToSummaryEntry), ...cappedEntries]);
}
export function getCappedDiffForSource({
@@ -305,7 +318,10 @@ export function getCappedDiffForSource({
lastTurnCapped,
}: {
source: ReviewSource;
- worktreeCapped?: { staged: ReviewCappedDiffData | null; unstaged: ReviewCappedDiffData | null } | null;
+ worktreeCapped?: {
+ staged: ReviewCappedDiffData | null;
+ unstaged: ReviewCappedDiffData | null;
+ } | null;
commitCapped?: ReviewCappedDiffData | null;
branchCapped?: ReviewCappedDiffData | null;
lastTurnCapped?: ReviewCappedDiffData | null;
@@ -352,17 +368,19 @@ export function scrollElementIntoContainerView(
}
export function shouldFallbackFromMissingSelectedCommit(
- source: ReviewSource,
+ source: ReviewSource | 'turn',
selectedCommitOid: string | null,
commits: readonly Pick<ReviewCommit, 'oid'>[],
commitsLoaded: boolean,
commitsLoading = false,
): boolean {
- return source === 'commit' &&
+ return (
+ source === 'commit' &&
commitsLoaded &&
!commitsLoading &&
Boolean(selectedCommitOid) &&
- !commits.some((commit) => commit.oid === selectedCommitOid);
+ !commits.some((commit) => commit.oid === selectedCommitOid)
+ );
}
export function getCurrentBranchDiffData(
@@ -371,18 +389,18 @@ export function getCurrentBranchDiffData(
): ReviewBranchDiffData | null {
if (!data) return null;
if (requestedBaseRef && data.baseRef !== requestedBaseRef) {
- const isRequestedBaseFallback = data.warning?.code === 'base-missing' &&
- data.warning.requestedBaseRef === requestedBaseRef;
+ const isRequestedBaseFallback =
+ data.warning?.code === 'base-missing' && data.warning.requestedBaseRef === requestedBaseRef;
if (!isRequestedBaseFallback) return null;
}
return data;
}
export function useClearReviewOperationNoticeOnSourceChange(
- source: ReviewSource,
+ source: ReviewSource | 'turn',
clearOperationNotice: () => void,
): void {
- const previousSourceRef = useRef<ReviewSource>(source);
+ const previousSourceRef = useRef<ReviewSource | 'turn'>(source);
useEffect(() => {
if (previousSourceRef.current === source) return;
previousSourceRef.current = source;
@@ -390,194 +408,17 @@ export function useClearReviewOperationNoticeOnSourceChange(
}, [clearOperationNotice, source]);
}
-export function ReviewTabBody(props: ReviewTabBodyProps) {
- const [source, setSource] = useState<ReviewSource>('unstaged');
- const [selectedCommitOid, setSelectedCommitOid] = useState<string | null>(null);
- if (props.state.turnTarget) {
- return (
- <TurnChangeSetReviewBody
- {...props}
- setSource={setSource}
- setSelectedCommitOid={setSelectedCommitOid}
- />
- );
- }
- return (
- <GitReviewTabBody
- {...props}
- source={source}
- setSource={setSource}
- selectedCommitOid={selectedCommitOid}
- setSelectedCommitOid={setSelectedCommitOid}
- />
- );
-}
-
-function TurnChangeSetReviewBody({ state, ctx, setSource, setSelectedCommitOid }: TurnReviewBodyProps) {
- const { t } = useTranslation();
- const target = state.turnTarget;
- // 变更集所属会话。协同面板里审查 worker 的轮次时,tab 桶在 lead 会话
- // (worker 自己的桶在协同视图下不可见),数据按 targetSessionId 取。
- const reviewSessionId = target?.targetSessionId ?? ctx.sessionId;
- const crossSession = Boolean(target?.targetSessionId && target.targetSessionId !== ctx.sessionId);
- // 供来源下拉的「提交」子菜单用;与 Git 视图同一 IPC,子菜单展开时刷新。
- // 跨会话时不挂来源下拉(git 视图跟随桶会话 workdir,对 worker 语义错误),
- // 传 null 跳过取数。
- const commitsState = useReviewCommits(crossSession ? null : ctx.sessionId || null, state.branchBaseRef ?? null);
- const switchToGitSource = useCallback((next: ReviewSource) => {
- // 对齐 Codex EP 语义:切到其它来源即退出轮次审查(清 turnTarget),
- // 轮次选择不保留;要再看本条消息需从聊天流卡片重新进入。
- setSelectedCommitOid(null);
- setSource(next);
- ctx.patchState({ turnTarget: null });
- }, [ctx, setSelectedCommitOid, setSource]);
- const switchToCommitSource = useCallback((oid: string) => {
- setSelectedCommitOid(oid);
- setSource('commit');
- ctx.patchState({ turnTarget: null });
- }, [ctx, setSelectedCommitOid, setSource]);
- const [changeSets, setChangeSets] = useState<TurnChangeSetDetail[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [reloadToken, setReloadToken] = useState(0);
- const targetIdsKey = target?.changeSetIds.join('\0') ?? '';
- const diffs = useMemo(() => changeSets.flatMap((set) => set.diffs), [changeSets]);
- const isPartial = changeSets.some((set) => set.state === 'partial');
- const collapsedSet = useMemo(() => new Set(state.collapsedPaths ?? []), [state.collapsedPaths]);
- const visibleDiffs = useMemo(
- () => filterWhitespaceHiddenDiffs(diffs, state.hideWhitespace ?? false),
- [diffs, state.hideWhitespace],
- );
- const expandedSet = useMemo(
- () => getExpandedDiffSet(visibleDiffs, collapsedSet),
- [collapsedSet, visibleDiffs],
- );
-
- useEffect(() => {
- if (!targetIdsKey) return;
- let cancelled = false;
- setLoading(true);
- setError(null);
- if (ctx.remoteHostId !== null || ctx.deviceLinkDeviceId !== null) {
- setChangeSets([]);
- setError(t('rightSidebar.review.turn.localOnly'));
- setLoading(false);
- return;
- }
- void window.electronAPI.maker.getTurnChangeSets(reviewSessionId, targetIdsKey.split('\0'))
- .then((sets) => {
- if (cancelled) return;
- setChangeSets(sets);
- })
- .catch((reason: unknown) => {
- if (cancelled) return;
- setError(extractIpcError(reason)?.message ?? (reason instanceof Error ? reason.message : String(reason)));
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [ctx.deviceLinkDeviceId, ctx.remoteHostId, reloadToken, reviewSessionId, t, targetIdsKey]);
-
- const selectedDiff = target?.selectedDiffId
- ? visibleDiffs.find((diff) => diff.id === target.selectedDiffId)
- : target?.selectedPath
- ? visibleDiffs.find((diff) => diff.path === target.selectedPath || diff.oldPath === target.selectedPath)
- : null;
- const jumpRequest = selectedDiff && target
- ? { id: selectedDiff.id, nonce: target.requestNonce }
- : null;
- const togglePath = useCallback((id: string) => {
- const next = new Set(collapsedSet);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- ctx.patchState({ collapsedPaths: Array.from(next) });
- }, [collapsedSet, ctx]);
- const totalAdd = visibleDiffs.reduce((sum, diff) => sum + diff.additions, 0);
- const totalDel = visibleDiffs.reduce((sum, diff) => sum + diff.deletions, 0);
- const unavailablePreview = useCallback(() => Promise.reject(new Error('Historical preview unavailable')), []);
-
- return (
- <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
- <header className="flex min-h-12 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-3 py-2">
- {crossSession ? (
- // 跨会话(协同 worker 的轮次):不提供 git 来源切换——git 视图跟随
- // 桶会话的 workdir,对 worker 的 worktree 语义错误。静态标题,关 tab 退出。
- <>
- <FileDiffIcon size={15} className="shrink-0 text-[var(--text-secondary)]" />
- <span className="min-w-0 truncate text-12 font-medium text-[var(--text-primary)]">
- {t('rightSidebar.review.turn.title')}
- </span>
- </>
- ) : (
- <SourceDropdown
- source="turn"
- counts={{}}
- commits={commitsState.data?.commits ?? []}
- commitsLoading={commitsState.loading}
- commitsError={commitsState.error}
- commitsLoaded={commitsState.data !== null}
- selectedCommitOid={null}
- onChange={switchToGitSource}
- onSelectCommit={switchToCommitSource}
- onRefreshCommits={commitsState.refresh}
- />
- )}
- <span className="min-w-0 flex-1 truncate" />
- <span className="shrink-0 whitespace-nowrap font-mono text-11 tabular-nums">
- <span className="text-[var(--diff-add-fg)]">+{totalAdd}</span>{' '}
- <span className="text-[var(--diff-del-fg)]">-{totalDel}</span>
- </span>
- </header>
- {!loading && !error && isPartial && (
- <div className="flex shrink-0 items-start gap-2 border-b border-[var(--border-default)] bg-[var(--warning-bg-soft)] px-3 py-2 text-11 leading-relaxed text-[var(--text-secondary)]">
- <AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" />
- <span>{t('rightSidebar.review.turn.partialNotice')}</span>
- </div>
- )}
- {loading ? (
- <CenteredState icon={<Spinner size={24} />} title={t('rightSidebar.review.loadingTitle')} desc={t('rightSidebar.review.loadingDesc')} />
- ) : error ? (
- <CenteredState
- icon={<AlertTriangle size={24} />}
- title={t('rightSidebar.review.errorTitle')}
- desc={error}
- actionLabel={t('rightSidebar.review.refresh')}
- onAction={() => setReloadToken((value) => value + 1)}
- />
- ) : visibleDiffs.length === 0 ? (
- <CenteredState
- icon={<FileDiffIcon size={24} />}
- title={t('rightSidebar.review.turn.emptyTitle')}
- desc={t('rightSidebar.review.turn.emptyDesc')}
- />
- ) : (
- <DiffList
- diffs={visibleDiffs}
- expandedSet={expandedSet}
- onToggleDiff={togglePath}
- onRefresh={() => setReloadToken((value) => value + 1)}
- refreshPending={loading}
- viewMode={state.diffViewMode ?? 'unified'}
- onViewModeChange={(diffViewMode) => ctx.patchState({ diffViewMode })}
- onRichMarkdownPreviewChange={(richMarkdownPreview) => ctx.patchState({ richMarkdownPreview })}
- wordWrap={state.wordWrap ?? false}
- wordDiff={state.wordDiff ?? false}
- fileTreeVisible={state.fileTreeVisible ?? false}
- jumpRequest={jumpRequest}
- loadImagePreview={unavailablePreview}
- loadMarkdownPreview={unavailablePreview}
- richMarkdownPreview={false}
- onOpenFile={() => undefined}
- />
- )}
- </div>
- );
+export function reviewSourceStatePatch(descriptor: ReviewSourceDescriptor) {
+ return {
+ descriptor,
+ jumpTarget: null,
+ // A partial state merge cannot delete the deprecated field. Null prevents
+ // legacy migration from reviving the previous historical source.
+ turnTarget: null,
+ };
}
-function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, setSelectedCommitOid }: GitReviewBodyProps) {
+export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
// device-link 远程会话:session 行在被控设备的 DB 里,只读查询经 gitReviewTransport
@@ -586,12 +427,61 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const deviceLinkDeviceId = ctx.deviceLinkDeviceId ?? null;
const sessionId = ctx.sessionId || null;
const hideWhitespace = state.hideWhitespace ?? false;
- const branchBaseRef = state.branchBaseRef ?? null;
- const { data, loading, error, errorCode, refresh, setData: setReviewData } = useReviewGitState(sessionId, hideWhitespace, deviceLinkDeviceId);
- const commitsState = useReviewCommits(sessionId, branchBaseRef, deviceLinkDeviceId);
+ const descriptor = state.descriptor;
+ 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;
+ const effectiveCommitOid = selectedCommitOid;
+ const crossSession =
+ descriptor.kind === 'turn-set' &&
+ Boolean(descriptor.targetSessionId && descriptor.targetSessionId !== sessionId);
+ const capabilities = useMemo(() => {
+ const sourceCapabilities = capabilitiesFor(descriptor);
+ return {
+ ...sourceCapabilities,
+ canSwitchSource:
+ descriptor.kind === 'turn-set' && crossSession ? false : sourceCapabilities.canSwitchSource,
+ };
+ }, [crossSession, descriptor]);
+ const setDescriptor = useCallback(
+ (nextDescriptor: ReviewSourceDescriptor) => {
+ ctx.patchState(reviewSourceStatePatch(nextDescriptor));
+ },
+ [ctx],
+ );
+ const setSource = useCallback(
+ (nextSource: ReviewSource) => {
+ const nextDescriptor: ReviewSourceDescriptor =
+ nextSource === 'commit'
+ ? { kind: 'commit', commitOid: null }
+ : nextSource === 'branch'
+ ? { kind: 'branch', baseRef: null }
+ : { kind: nextSource };
+ setDescriptor(nextDescriptor);
+ },
+ [setDescriptor],
+ );
+ const sourceState = useReviewSource(descriptor, sessionId, {
+ hideWhitespace,
+ deviceLinkDeviceId,
+ remoteHostId: ctx.remoteHostId,
+ });
+ const data = sourceState.reviewData;
+ const loading = sourceState.loading;
+ const error = sourceState.error;
+ const errorCode = sourceState.gitErrorCode;
+ const refresh = sourceState.refreshGit;
+ const setReviewData = sourceState.setReviewData;
+ const commitsState = useReviewCommits(
+ capabilities.canSwitchSource ? sessionId : null,
+ branchBaseRef,
+ deviceLinkDeviceId,
+ );
const [pendingKey, setPendingKey] = useState<string | null>(null);
const [operationError, setOperationError] = useState<string | null>(null);
- const [operationSummary, setOperationSummary] = useState<ReviewStageOperationSummary | null>(null);
+ const [operationSummary, setOperationSummary] = useState<ReviewStageOperationSummary | null>(
+ null,
+ );
const [jumpRequest, setJumpRequest] = useState<ReviewFileJumpRequest | null>(null);
const [selectedCappedFileId, setSelectedCappedFileId] = useState<string | null>(null);
const [reviewWriteVersion, setReviewWriteVersion] = useState(0);
@@ -601,7 +491,6 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
// 消失时 setState 触发 effect 重挂,才能覆盖所有渲染分支切换。
const [headerEl, setHeaderEl] = useState<HTMLElement | null>(null);
const [headerWidth, setHeaderWidth] = useState(0);
- const lastTurnPaths = useLastTurnFilter(sessionId, data?.scope.repoRoot ?? null);
const runningSnapshot = useSyncExternalStore(
makerChatStore.subscribeAll,
makerChatStore.getRunningSnapshot,
@@ -618,112 +507,86 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const rawUnstaged = data?.diffs.unstaged ?? [];
const rawStaged = data?.diffs.staged ?? [];
const worktreeCapped = data?.diffs.capped ?? null;
- const unstaged = useMemo(() => filterWhitespaceHiddenDiffs(rawUnstaged, hideWhitespace), [hideWhitespace, rawUnstaged]);
- const staged = useMemo(() => filterWhitespaceHiddenDiffs(rawStaged, hideWhitespace), [hideWhitespace, rawStaged]);
- const commits = commitsState.data?.commits ?? [];
- const effectiveCommitOid = source === 'commit' ? selectedCommitOid : null;
- const commitDiffState = useReviewCommitDiff(sessionId, effectiveCommitOid, hideWhitespace, deviceLinkDeviceId);
- const branchDiffState = useReviewBranchDiff(sessionId, branchBaseRef, hideWhitespace, source === 'branch', deviceLinkDeviceId);
- const currentBranchDiffData = getCurrentBranchDiffData(branchDiffState.data, branchBaseRef);
- const availableLastTurnDiffs = useMemo(
- () => rawUnstaged.concat(rawStaged).filter((diff) => lastTurnPaths.has(diff.path)),
- [lastTurnPaths, rawStaged, rawUnstaged],
- );
- const lastTurnCappedEntries = useMemo(
- () => getLastTurnCappedSummaryEntries(worktreeCapped, lastTurnPaths),
- [lastTurnPaths, worktreeCapped],
+ const unstaged = useMemo(
+ () => filterWhitespaceHiddenDiffs(rawUnstaged, hideWhitespace),
+ [hideWhitespace, rawUnstaged],
);
- const lastTurnCapped = useMemo<ReviewCappedDiffData | null>(
- () => buildLastTurnCappedData(availableLastTurnDiffs, lastTurnCappedEntries),
- [availableLastTurnDiffs, lastTurnCappedEntries],
+ const staged = useMemo(
+ () => filterWhitespaceHiddenDiffs(rawStaged, hideWhitespace),
+ [hideWhitespace, rawStaged],
);
- const lastTurnHydrationRequests = useMemo(() => {
- if (source !== 'last-turn' || lastTurnCapped || lastTurnCappedEntries.length === 0) return [];
- return lastTurnCappedEntries.map((entry) => ({
- source: entry.source,
- path: entry.path,
- oldPath: entry.oldPath,
- commitOid: null,
- branchBaseRef: null,
- ignoreWhitespace: hideWhitespace,
- }));
- }, [hideWhitespace, lastTurnCapped, lastTurnCappedEntries, source]);
- const lastTurnHydratedDiffState = useReviewFileDiffs(sessionId, lastTurnHydrationRequests, deviceLinkDeviceId);
- const hydratedLastTurnDiffs = useMemo(
- () => lastTurnHydratedDiffState.data?.map((item) => item.diff).filter((diff): diff is FileDiff => diff !== null) ?? [],
- [lastTurnHydratedDiffState.data],
- );
- const rawLastTurnDiffs = useMemo(
- () => availableLastTurnDiffs.concat(hydratedLastTurnDiffs),
- [availableLastTurnDiffs, hydratedLastTurnDiffs],
- );
- const lastTurnDiffs = useMemo(
- () => filterWhitespaceHiddenDiffs(rawLastTurnDiffs, hideWhitespace),
- [hideWhitespace, rawLastTurnDiffs],
- );
- const selectedCommitDiff = commitDiffState.data?.commitOid === effectiveCommitOid ? commitDiffState.data : null;
+ const commits = commitsState.data?.commits ?? [];
+ const currentBranchDiffData = sourceState.branchData;
+ const selectedCommitDiff = sourceState.commitData;
const rawCommitDiffs = selectedCommitDiff?.diffs ?? [];
- const commitCapped = selectedCommitDiff?.capped ?? null;
- const commitDiffs = useMemo(() => filterWhitespaceHiddenDiffs(rawCommitDiffs, hideWhitespace), [hideWhitespace, rawCommitDiffs]);
const rawBranchDiffs = currentBranchDiffData?.diffs ?? [];
- const branchCapped = currentBranchDiffData?.capped ?? null;
- const branchDiffs = useMemo(() => filterWhitespaceHiddenDiffs(rawBranchDiffs, hideWhitespace), [hideWhitespace, rawBranchDiffs]);
const platform = window.electronAPI?.platform ?? '';
- const branchCandidates = branchDiffState.data?.candidates ?? [];
- const selectedBranchBaseRef = branchBaseRef && branchCandidates.some((candidate) => candidate.refName === branchBaseRef)
- ? branchBaseRef
- : currentBranchDiffData?.baseRef ?? branchBaseRef;
- const currentCapped = getCappedDiffForSource({
- source,
- worktreeCapped,
- commitCapped,
- branchCapped,
- lastTurnCapped,
- });
+ const branchCandidates = currentBranchDiffData?.candidates ?? [];
+ const selectedBranchBaseRef =
+ branchBaseRef && branchCandidates.some((candidate) => candidate.refName === branchBaseRef)
+ ? branchBaseRef
+ : (currentBranchDiffData?.baseRef ?? branchBaseRef);
+ const currentCapped = sourceState.capped;
const cappedSummaryDiffs = useMemo(
- () => currentCapped ? currentCapped.files.map(summaryEntryToPlaceholderDiff) : [],
+ () => (currentCapped ? currentCapped.files.map(summaryEntryToPlaceholderDiff) : []),
[currentCapped],
);
- const visibleDiffs = currentCapped
- ? cappedSummaryDiffs
- : source === 'commit'
- ? commitDiffs
- : source === 'branch'
- ? branchDiffs
- : source === 'staged'
- ? staged
- : source === 'last-turn'
- ? lastTurnDiffs
- : unstaged;
+ const visibleDiffs = currentCapped ? cappedSummaryDiffs : sourceState.diffs;
const expandedSet = useMemo(
() => getExpandedDiffSet(visibleDiffs, collapsedSet),
[collapsedSet, visibleDiffs],
);
+ const entryJumpDiff = state.jumpTarget?.diffId
+ ? visibleDiffs.find((diff) => diff.id === state.jumpTarget?.diffId)
+ : state.jumpTarget?.path
+ ? visibleDiffs.find(
+ (diff) => diff.path === state.jumpTarget?.path || diff.oldPath === state.jumpTarget?.path,
+ )
+ : null;
+ const resolvedJumpRequest =
+ jumpRequest ??
+ (entryJumpDiff && state.jumpTarget
+ ? { id: entryJumpDiff.id, nonce: state.jumpTarget.nonce }
+ : null);
const selectedCappedSummaryDiff = currentCapped
- ? cappedSummaryDiffs.find((diff) => diff.id === selectedCappedFileId) ?? cappedSummaryDiffs[0] ?? null
+ ? (cappedSummaryDiffs.find((diff) => diff.id === selectedCappedFileId) ??
+ cappedSummaryDiffs[0] ??
+ null)
+ : null;
+ const expansionDiffs =
+ currentCapped && selectedCappedSummaryDiff ? [selectedCappedSummaryDiff] : visibleDiffs;
+ const cappedFileDiffRequest = selectedCappedSummaryDiff
+ ? {
+ source: selectedCappedSummaryDiff.source,
+ path: selectedCappedSummaryDiff.path,
+ oldPath: selectedCappedSummaryDiff.oldPath,
+ commitOid: selectedCappedSummaryDiff.source === 'commit' ? effectiveCommitOid : null,
+ branchBaseRef:
+ selectedCappedSummaryDiff.source === 'branch'
+ ? (currentBranchDiffData?.baseRef ?? branchBaseRef)
+ : null,
+ ignoreWhitespace: hideWhitespace,
+ }
: null;
- const expansionDiffs = currentCapped && selectedCappedSummaryDiff ? [selectedCappedSummaryDiff] : visibleDiffs;
- const cappedFileDiffRequest = selectedCappedSummaryDiff ? {
- source: selectedCappedSummaryDiff.source,
- path: selectedCappedSummaryDiff.path,
- oldPath: selectedCappedSummaryDiff.oldPath,
- commitOid: selectedCappedSummaryDiff.source === 'commit' ? effectiveCommitOid : null,
- branchBaseRef: selectedCappedSummaryDiff.source === 'branch' ? currentBranchDiffData?.baseRef ?? branchBaseRef : null,
- ignoreWhitespace: hideWhitespace,
- } : null;
- const cappedFileDiffState = useReviewFileDiff(sessionId, cappedFileDiffRequest, reviewWriteVersion, deviceLinkDeviceId);
+ const cappedFileDiffState = useReviewFileDiff(
+ sessionId,
+ cappedFileDiffRequest,
+ reviewWriteVersion,
+ deviceLinkDeviceId,
+ );
const cappedFileDiffData = cappedFileDiffState.data;
const maybeCappedLoadedDiff = cappedFileDiffData?.diff ?? null;
- const cappedLoadedDiff = maybeCappedLoadedDiff?.id === selectedCappedSummaryDiff?.id
- ? maybeCappedLoadedDiff
- : null;
- const lastTurnHydrating = source === 'last-turn' &&
- lastTurnHydrationRequests.length > 0 &&
- lastTurnHydratedDiffState.loading &&
- hydratedLastTurnDiffs.length < lastTurnHydrationRequests.length;
- const lastTurnHydrationError = source === 'last-turn' ? lastTurnHydratedDiffState.error : null;
+ const cappedLoadedDiff =
+ maybeCappedLoadedDiff?.id === selectedCappedSummaryDiff?.id ? maybeCappedLoadedDiff : null;
+ const lastTurnHydrating =
+ source === 'last-turn' && sourceState.loading && sourceState.diffs.length === 0;
+ const lastTurnHydrationError = source === 'last-turn' ? sourceState.error : null;
const expansionToggle = useMemo(
- () => getReviewDiffExpansionToggle(expansionDiffs.map((diff) => diff.id), collapsedSet),
+ () =>
+ getReviewDiffExpansionToggle(
+ expansionDiffs.map((diff) => diff.id),
+ collapsedSet,
+ ),
[collapsedSet, expansionDiffs],
);
const gitApplyAvailability = useMemo(
@@ -735,76 +598,144 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
* 等大字段以节省帧预算。markdownReader 额外读取 kind/size/status/isTooLarge/isBinary,
* imageReader 读取 kind。本地调用仍传完整 diff 保持兼容。
*/
- const trimPreviewDiff = useCallback((diff: FileDiff): FileDiff => ({
- source: diff.source,
- id: diff.id,
- path: diff.path,
- oldPath: diff.oldPath,
- index: diff.index,
- kind: diff.kind,
- size: diff.size,
- status: diff.status,
- isTooLarge: diff.isTooLarge,
- isBinary: diff.isBinary,
- } as FileDiff), []);
- const loadImagePreview = useCallback<LoadImagePreview>((diff) => {
- if (!sessionId) return Promise.reject(new Error('sessionId is required'));
- return gitReviewApiFor(deviceLinkDeviceId).imagePreview({
+ const trimPreviewDiff = useCallback(
+ (diff: FileDiff): FileDiff =>
+ ({
+ source: diff.source,
+ id: diff.id,
+ path: diff.path,
+ oldPath: diff.oldPath,
+ index: diff.index,
+ kind: diff.kind,
+ size: diff.size,
+ status: diff.status,
+ isTooLarge: diff.isTooLarge,
+ isBinary: diff.isBinary,
+ }) as FileDiff,
+ [],
+ );
+ const loadImagePreview = useCallback<LoadImagePreview>(
+ (diff) => {
+ if (!sessionId) return Promise.reject(new Error('sessionId is required'));
+ return gitReviewApiFor(deviceLinkDeviceId)
+ .imagePreview({
+ sessionId,
+ diff: deviceLinkDeviceId ? trimPreviewDiff(diff) : diff,
+ commitOid: diff.source === 'commit' ? effectiveCommitOid : null,
+ branchBaseRef:
+ diff.source === 'branch' ? (currentBranchDiffData?.baseRef ?? branchBaseRef) : null,
+ } as Parameters<typeof window.electronAPI.gitReview.imagePreview>[0])
+ .catch((err) => {
+ if (isReviewRemoteOversizeError(err))
+ throw new Error(t('rightSidebar.review.remote.oversizeDesc'));
+ throw err;
+ });
+ },
+ [
+ branchBaseRef,
+ currentBranchDiffData?.baseRef,
+ deviceLinkDeviceId,
+ effectiveCommitOid,
sessionId,
- diff: deviceLinkDeviceId ? trimPreviewDiff(diff) : diff,
- commitOid: diff.source === 'commit' ? effectiveCommitOid : null,
- branchBaseRef: diff.source === 'branch' ? currentBranchDiffData?.baseRef ?? branchBaseRef : null,
- } as Parameters<typeof window.electronAPI.gitReview.imagePreview>[0]).catch((err) => {
- if (isReviewRemoteOversizeError(err)) throw new Error(t('rightSidebar.review.remote.oversizeDesc'));
- throw err;
- });
- }, [branchBaseRef, currentBranchDiffData?.baseRef, deviceLinkDeviceId, effectiveCommitOid, sessionId, t, trimPreviewDiff]);
- const loadMarkdownPreview = useCallback<LoadMarkdownPreview>((diff) => {
- if (!sessionId) return Promise.reject(new Error('sessionId is required'));
- return gitReviewApiFor(deviceLinkDeviceId).markdownPreview({
+ t,
+ trimPreviewDiff,
+ ],
+ );
+ const loadMarkdownPreview = useCallback<LoadMarkdownPreview>(
+ (diff) => {
+ if (!sessionId) return Promise.reject(new Error('sessionId is required'));
+ return gitReviewApiFor(deviceLinkDeviceId)
+ .markdownPreview({
+ sessionId,
+ diff: deviceLinkDeviceId ? trimPreviewDiff(diff) : diff,
+ commitOid: diff.source === 'commit' ? effectiveCommitOid : null,
+ branchBaseRef:
+ diff.source === 'branch' ? (currentBranchDiffData?.baseRef ?? branchBaseRef) : null,
+ } as Parameters<typeof window.electronAPI.gitReview.markdownPreview>[0])
+ .catch((err) => {
+ if (isReviewRemoteOversizeError(err))
+ throw new Error(t('rightSidebar.review.remote.oversizeDesc'));
+ throw err;
+ });
+ },
+ [
+ branchBaseRef,
+ currentBranchDiffData?.baseRef,
+ deviceLinkDeviceId,
+ effectiveCommitOid,
sessionId,
- diff: deviceLinkDeviceId ? trimPreviewDiff(diff) : diff,
- commitOid: diff.source === 'commit' ? effectiveCommitOid : null,
- branchBaseRef: diff.source === 'branch' ? currentBranchDiffData?.baseRef ?? branchBaseRef : null,
- } as Parameters<typeof window.electronAPI.gitReview.markdownPreview>[0]).catch((err) => {
- if (isReviewRemoteOversizeError(err)) throw new Error(t('rightSidebar.review.remote.oversizeDesc'));
- throw err;
- });
- }, [branchBaseRef, currentBranchDiffData?.baseRef, deviceLinkDeviceId, effectiveCommitOid, sessionId, t, trimPreviewDiff]);
- const openReviewFile = useCallback((diff: FileDiff) => {
- if (!sessionId) return;
- void window.electronAPI.gitReview.openFile({ sessionId, path: diff.path })
- .catch((err) => {
- const message = extractIpcError(err)?.message ?? (err instanceof Error ? err.message : String(err));
+ t,
+ trimPreviewDiff,
+ ],
+ );
+ const unavailableHistoricalPreview = useCallback(
+ () => Promise.reject(new Error(t('rightSidebar.review.turn.previewUnavailable'))),
+ [t],
+ );
+ const openReviewFile = useCallback(
+ (diff: FileDiff) => {
+ if (!sessionId) return;
+ void window.electronAPI.gitReview.openFile({ sessionId, path: diff.path }).catch((err) => {
+ const message =
+ extractIpcError(err)?.message ?? (err instanceof Error ? err.message : String(err));
toast.error(t('rightSidebar.review.openFileFailed', { error: message }));
});
- }, [sessionId, t]);
+ },
+ [sessionId, t],
+ );
// device-link 与 SSH 工作区都没有可由控制端 shell 打开的本机文件。
- const openFileHandler = shouldOfferReviewOpenFile(ctx.remoteHostId, deviceLinkDeviceId) ? openReviewFile : undefined;
+ const openFileHandler =
+ capabilities.canOpenFile && shouldOfferReviewOpenFile(ctx.remoteHostId, deviceLinkDeviceId)
+ ? openReviewFile
+ : undefined;
// 次级视图(提交 / 分支 / 单文件)错误串的 OVERSIZE 标记 → 可读文案;其余原样。
- const localizeReviewError = useCallback(<T extends string | null>(message: T): T | string => {
- if (message && isReviewRemoteOversizeError(message)) return t('rightSidebar.review.remote.oversizeDesc');
- return message;
- }, [t]);
+ const localizeReviewError = useCallback(
+ <T extends string | null>(message: T): T | string => {
+ if (message && isReviewRemoteOversizeError(message))
+ return t('rightSidebar.review.remote.oversizeDesc');
+ return message;
+ },
+ [t],
+ );
const writeDisabledReasons = data?.status?.writeDisabledReasons ?? [];
const effectiveWriteDisabledReasons = useMemo(() => {
const reasons = [...writeDisabledReasons];
+ if (!capabilities.canCommit || !capabilities.canPush) reasons.push('historical-snapshot');
// device-link 首期只读:被控端 handler 也不实现写 op,这里是同一契约的 UI 面。
if (deviceLinkDeviceId) reasons.push('remote-device');
if (agentRunning) reasons.push('agent-running');
- return reasons;
- }, [agentRunning, deviceLinkDeviceId, writeDisabledReasons]);
- const canWrite = Boolean(data?.status && effectiveWriteDisabledReasons.length === 0 && !pendingKey);
- const commitOrPushPending = pendingKey === 'commit' || pendingKey === 'commit-push' || pendingKey === 'push';
+ return Array.from(new Set(reasons));
+ }, [
+ agentRunning,
+ capabilities.canCommit,
+ capabilities.canPush,
+ deviceLinkDeviceId,
+ writeDisabledReasons,
+ ]);
+ const canWrite = Boolean(
+ capabilities.canCommit &&
+ capabilities.canPush &&
+ data?.status &&
+ effectiveWriteDisabledReasons.length === 0 &&
+ !pendingKey,
+ );
+ const commitOrPushPending =
+ pendingKey === 'commit' || pendingKey === 'commit-push' || pendingKey === 'push';
const pushPending = pendingKey === 'push' || pendingKey === 'commit-push';
const writeDisabledReasonText = effectiveWriteDisabledReasons
- .map((reason) => t(`rightSidebar.review.writeDisabledReasons.${reason}`, { defaultValue: reason }))
+ .map((reason) =>
+ t(`rightSidebar.review.writeDisabledReasons.${reason}`, { defaultValue: reason }),
+ )
.join(', ');
const actionWriteDisabledTooltip = writeDisabledReasonText
- ? t('rightSidebar.review.actions.disabledWriteGateWithReasons', { reasons: writeDisabledReasonText })
+ ? t('rightSidebar.review.actions.disabledWriteGateWithReasons', {
+ reasons: writeDisabledReasonText,
+ })
: undefined;
const pushWriteDisabledText = writeDisabledReasonText
- ? t('rightSidebar.review.push.disabledWriteGateWithReasons', { reasons: writeDisabledReasonText })
+ ? t('rightSidebar.review.push.disabledWriteGateWithReasons', {
+ reasons: writeDisabledReasonText,
+ })
: undefined;
const totalAdd = visibleDiffs.reduce((sum, diff) => sum + diff.additions, 0);
const totalDel = visibleDiffs.reduce((sum, diff) => sum + diff.deletions, 0);
@@ -812,7 +743,7 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const statusUnstagedCount = data?.status?.unstagedCount ?? rawUnstaged.length;
const sourceUnstagedCount = worktreeCapped?.unstaged?.stats.fileCount ?? unstaged.length;
const sourceStagedCount = worktreeCapped?.staged?.stats.fileCount ?? staged.length;
- const sourceLastTurnCount = lastTurnCapped?.stats.fileCount ?? availableLastTurnDiffs.length + lastTurnCappedEntries.length;
+ const sourceLastTurnCount = sourceState.lastTurnCount;
const clearOperationNotice = useCallback(() => {
setOperationError(null);
@@ -823,144 +754,179 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const refreshAll = useCallback(() => {
clearOperationNotice();
- refresh();
+ sourceState.refresh();
commitsState.refresh();
- if (source === 'commit') commitDiffState.refresh();
- if (source === 'branch') branchDiffState.refresh();
if (currentCapped) cappedFileDiffState.refresh();
- if (source === 'last-turn') lastTurnHydratedDiffState.refresh();
- }, [branchDiffState, cappedFileDiffState, clearOperationNotice, commitDiffState, commitsState, currentCapped, lastTurnHydratedDiffState, refresh, source]);
-
- const messageFromOperationError = useCallback((err: unknown): string => {
- const ipcError = extractIpcError(err);
- if (ipcError?.code === 'STALE_DIFF') return t('rightSidebar.review.staleDiff');
- if (ipcError?.code === 'SESSION_RUNNING') return t('rightSidebar.review.sessionRunningWriteBlocked');
- if (ipcError?.code === 'PUSH_LEASE_EXPIRED') return t('rightSidebar.review.push.leaseExpired');
- if (ipcError?.code === 'PUSH_NO_REMOTE') return t('rightSidebar.review.push.noRemote');
- return ipcError?.message ?? (err instanceof Error ? err.message : String(err));
- }, [t]);
+ }, [cappedFileDiffState, clearOperationNotice, commitsState, currentCapped, sourceState]);
+
+ const messageFromOperationError = useCallback(
+ (err: unknown): string => {
+ const ipcError = extractIpcError(err);
+ if (ipcError?.code === 'STALE_DIFF') return t('rightSidebar.review.staleDiff');
+ if (ipcError?.code === 'SESSION_RUNNING')
+ return t('rightSidebar.review.sessionRunningWriteBlocked');
+ if (ipcError?.code === 'PUSH_LEASE_EXPIRED')
+ return t('rightSidebar.review.push.leaseExpired');
+ if (ipcError?.code === 'PUSH_NO_REMOTE') return t('rightSidebar.review.push.noRemote');
+ return ipcError?.message ?? (err instanceof Error ? err.message : String(err));
+ },
+ [t],
+ );
// 写操作共用的 pending/错误/收尾样板:失败时保留当前视图并触发 refresh。
- const runWrite = useCallback(async (
- key: string,
- exec: () => Promise<void>,
- decorateError?: (message: string, err: unknown) => string,
- ): Promise<boolean> => {
- setPendingKey(key);
- clearOperationNotice();
- try {
- await exec();
- return true;
- } catch (err) {
- const message = messageFromOperationError(err);
- setOperationError(decorateError ? decorateError(message, err) : message);
- refresh();
- return false;
- } finally {
- setPendingKey(null);
- }
- }, [clearOperationNotice, messageFromOperationError, refresh]);
- const updateReviewDataFromWrite = useCallback((nextData: typeof data) => {
- if (!nextData) return;
- setReviewWriteVersion((version) => version + 1);
- if (hideWhitespace) {
- refresh();
- return;
- }
- setReviewData(nextData);
- }, [hideWhitespace, refresh, setReviewData]);
-
- const runStageOperation = useCallback((
- action: ReviewToggleAction,
- targets: ReviewFileTarget[],
- key: string,
- ) => {
- if (!sessionId || targets.length === 0) return;
- void runWrite(key, async () => {
- const api = action === 'stage'
- ? targets.length === 1 ? window.electronAPI.gitReview.stageFile : window.electronAPI.gitReview.stageAll
- : targets.length === 1 ? window.electronAPI.gitReview.unstageFile : window.electronAPI.gitReview.unstageAll;
- const result = await api({ sessionId, targets });
- updateReviewDataFromWrite(result.data);
- setOperationSummary(result.operation);
- });
- }, [runWrite, sessionId, updateReviewDataFromWrite]);
-
- const runHunkOperation = useCallback((
- action: ReviewToggleAction,
- diff: FileDiff,
- hunkIndex: number,
- ) => {
- if (!sessionId) return;
- void runWrite(`${action}:hunk:${diff.id}:${hunkIndex}`, async () => {
- const api = action === 'stage' ? window.electronAPI.gitReview.stageHunk : window.electronAPI.gitReview.unstageHunk;
- const result = await api({ sessionId, diff, hunkIndex, ignoreWhitespace: hideWhitespace });
- updateReviewDataFromWrite(result.data);
- setOperationSummary(result.operation);
- });
- }, [hideWhitespace, runWrite, sessionId, updateReviewDataFromWrite]);
-
- const confirmDiscard = useCallback(async (
- scope: 'file' | 'hunk' | 'section',
- diffs: FileDiff[],
- ): Promise<boolean> => {
- const untrackedCount = diffs.filter((diff) => diff.status === 'untracked').length;
- return confirm({
- title: t(`rightSidebar.review.discard.confirm.${scope}.title`, { count: diffs.length }),
- description: untrackedCount > 0
- ? t(`rightSidebar.review.discard.confirm.${scope}.descWithUntracked`, {
- count: diffs.length,
- untrackedCount,
- })
- : t(`rightSidebar.review.discard.confirm.${scope}.desc`, { count: diffs.length }),
- confirmText: t('rightSidebar.review.discard.confirm.confirm'),
- cancelText: t('rightSidebar.review.discard.confirm.cancel'),
- });
- }, [confirm, t]);
+ const runWrite = useCallback(
+ async (
+ key: string,
+ exec: () => Promise<void>,
+ decorateError?: (message: string, err: unknown) => string,
+ ): Promise<boolean> => {
+ setPendingKey(key);
+ clearOperationNotice();
+ try {
+ await exec();
+ return true;
+ } catch (err) {
+ const message = messageFromOperationError(err);
+ setOperationError(decorateError ? decorateError(message, err) : message);
+ refresh();
+ return false;
+ } finally {
+ setPendingKey(null);
+ }
+ },
+ [clearOperationNotice, messageFromOperationError, refresh],
+ );
+ const updateReviewDataFromWrite = useCallback(
+ (nextData: typeof data) => {
+ if (!nextData) return;
+ setReviewWriteVersion((version) => version + 1);
+ if (hideWhitespace) {
+ refresh();
+ return;
+ }
+ setReviewData(nextData);
+ },
+ [hideWhitespace, refresh, setReviewData],
+ );
- const runDiscardFileOperation = useCallback((diff: FileDiff) => {
- if (!sessionId) return;
- void (async () => {
- if (!await confirmDiscard('file', [diff])) return;
- await runWrite(`discard:file:${diff.id}`, async () => {
- const result = await window.electronAPI.gitReview.discardFile({ sessionId, targets: [targetFromDiff(diff)] });
+ const runStageOperation = useCallback(
+ (action: ReviewToggleAction, targets: ReviewFileTarget[], key: string) => {
+ if (!sessionId || targets.length === 0) return;
+ void runWrite(key, async () => {
+ const api =
+ action === 'stage'
+ ? targets.length === 1
+ ? window.electronAPI.gitReview.stageFile
+ : window.electronAPI.gitReview.stageAll
+ : targets.length === 1
+ ? window.electronAPI.gitReview.unstageFile
+ : window.electronAPI.gitReview.unstageAll;
+ const result = await api({ sessionId, targets });
updateReviewDataFromWrite(result.data);
setOperationSummary(result.operation);
});
- })();
- }, [confirmDiscard, runWrite, sessionId, updateReviewDataFromWrite]);
+ },
+ [runWrite, sessionId, updateReviewDataFromWrite],
+ );
- const runDiscardHunkOperation = useCallback((diff: FileDiff, hunkIndex: number) => {
- if (!sessionId) return;
- void (async () => {
- if (!await confirmDiscard('hunk', [diff])) return;
- await runWrite(`discard:hunk:${diff.id}:${hunkIndex}`, async () => {
- const result = await window.electronAPI.gitReview.discardHunk({ sessionId, diff, hunkIndex, ignoreWhitespace: hideWhitespace });
+ const runHunkOperation = useCallback(
+ (action: ReviewToggleAction, diff: FileDiff, hunkIndex: number) => {
+ if (!sessionId) return;
+ void runWrite(`${action}:hunk:${diff.id}:${hunkIndex}`, async () => {
+ const api =
+ action === 'stage'
+ ? window.electronAPI.gitReview.stageHunk
+ : window.electronAPI.gitReview.unstageHunk;
+ const result = await api({ sessionId, diff, hunkIndex, ignoreWhitespace: hideWhitespace });
updateReviewDataFromWrite(result.data);
setOperationSummary(result.operation);
});
- })();
- }, [confirmDiscard, hideWhitespace, runWrite, sessionId, updateReviewDataFromWrite]);
-
- const runDiscardSectionOperation = useCallback((diffsToDiscard: FileDiff[], key: string) => {
- if (!sessionId || diffsToDiscard.length === 0) return;
- void (async () => {
- if (!await confirmDiscard('section', diffsToDiscard)) return;
- await runWrite(key, async () => {
- const result = await window.electronAPI.gitReview.discardAll({
- sessionId,
- targets: diffsToDiscard.map(targetFromDiff),
- });
- updateReviewDataFromWrite(result.data);
- setOperationSummary(result.operation);
+ },
+ [hideWhitespace, runWrite, sessionId, updateReviewDataFromWrite],
+ );
+
+ const confirmDiscard = useCallback(
+ async (scope: 'file' | 'hunk' | 'section', diffs: FileDiff[]): Promise<boolean> => {
+ const untrackedCount = diffs.filter((diff) => diff.status === 'untracked').length;
+ return confirm({
+ title: t(`rightSidebar.review.discard.confirm.${scope}.title`, { count: diffs.length }),
+ description:
+ untrackedCount > 0
+ ? t(`rightSidebar.review.discard.confirm.${scope}.descWithUntracked`, {
+ count: diffs.length,
+ untrackedCount,
+ })
+ : t(`rightSidebar.review.discard.confirm.${scope}.desc`, { count: diffs.length }),
+ confirmText: t('rightSidebar.review.discard.confirm.confirm'),
+ cancelText: t('rightSidebar.review.discard.confirm.cancel'),
});
- })();
- }, [confirmDiscard, runWrite, sessionId, updateReviewDataFromWrite]);
+ },
+ [confirm, t],
+ );
- const applyPushResult = useCallback((result: ReviewPushResult) => {
- updateReviewDataFromWrite(result.data);
- return result;
- }, [updateReviewDataFromWrite]);
+ const runDiscardFileOperation = useCallback(
+ (diff: FileDiff) => {
+ if (!sessionId) return;
+ void (async () => {
+ if (!(await confirmDiscard('file', [diff]))) return;
+ await runWrite(`discard:file:${diff.id}`, async () => {
+ const result = await window.electronAPI.gitReview.discardFile({
+ sessionId,
+ targets: [targetFromDiff(diff)],
+ });
+ updateReviewDataFromWrite(result.data);
+ setOperationSummary(result.operation);
+ });
+ })();
+ },
+ [confirmDiscard, runWrite, sessionId, updateReviewDataFromWrite],
+ );
+
+ const runDiscardHunkOperation = useCallback(
+ (diff: FileDiff, hunkIndex: number) => {
+ if (!sessionId) return;
+ void (async () => {
+ if (!(await confirmDiscard('hunk', [diff]))) return;
+ await runWrite(`discard:hunk:${diff.id}:${hunkIndex}`, async () => {
+ const result = await window.electronAPI.gitReview.discardHunk({
+ sessionId,
+ diff,
+ hunkIndex,
+ ignoreWhitespace: hideWhitespace,
+ });
+ updateReviewDataFromWrite(result.data);
+ setOperationSummary(result.operation);
+ });
+ })();
+ },
+ [confirmDiscard, hideWhitespace, runWrite, sessionId, updateReviewDataFromWrite],
+ );
+
+ const runDiscardSectionOperation = useCallback(
+ (diffsToDiscard: FileDiff[], key: string) => {
+ if (!sessionId || diffsToDiscard.length === 0) return;
+ void (async () => {
+ if (!(await confirmDiscard('section', diffsToDiscard))) return;
+ await runWrite(key, async () => {
+ const result = await window.electronAPI.gitReview.discardAll({
+ sessionId,
+ targets: diffsToDiscard.map(targetFromDiff),
+ });
+ updateReviewDataFromWrite(result.data);
+ setOperationSummary(result.operation);
+ });
+ })();
+ },
+ [confirmDiscard, runWrite, sessionId, updateReviewDataFromWrite],
+ );
+
+ const applyPushResult = useCallback(
+ (result: ReviewPushResult) => {
+ updateReviewDataFromWrite(result.data);
+ return result;
+ },
+ [updateReviewDataFromWrite],
+ );
const runPushFlow = useCallback(async () => {
if (!sessionId) return;
@@ -981,43 +947,74 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
});
if (!ok) return;
- const forceResult = applyPushResult(await window.electronAPI.gitReview.push({
- sessionId,
- confirmForce: {
- remoteRef: result.remoteRef,
- expectedOid: result.remoteOid,
- },
- }));
+ const forceResult = applyPushResult(
+ await window.electronAPI.gitReview.push({
+ sessionId,
+ confirmForce: {
+ remoteRef: result.remoteRef,
+ expectedOid: result.remoteOid,
+ },
+ }),
+ );
if (forceResult.kind === 'needs-force') {
throw new Error(t('rightSidebar.review.push.forceStillRejected'));
}
toast.success(t('rightSidebar.review.push.successToast'));
}, [applyPushResult, confirm, sessionId, t]);
- const decoratePushError = useCallback((message: string, err: unknown) => {
+ const decoratePushError = useCallback(
+ (message: string, err: unknown) => {
// lease/no-remote 已是完整本地化文案;其余(hook 拒绝/凭证/网络)保留 raw 细节,
// 但补一行本地化主文案,OperationNotice 会把首行做主展示。
- const code = extractIpcError(err)?.code;
- if (code === 'PUSH_LEASE_EXPIRED' || code === 'PUSH_NO_REMOTE' || code === 'SESSION_RUNNING') return message;
- return `${t('rightSidebar.review.push.failedTitle')}\n${message}`;
- }, [t]);
-
- const commitChanges = useCallback((message: string, includeUnstaged: boolean, pushAfterCommit: boolean): Promise<ReviewCommitRunResult> => {
- if (!sessionId) return Promise.resolve({ committed: false, completed: false });
- let committed = false;
- return runWrite(pushAfterCommit ? 'commit-push' : 'commit', async () => {
- const result = await window.electronAPI.gitReview.commit({ sessionId, message, includeUnstaged });
- committed = true;
- updateReviewDataFromWrite(result.data);
- setSelectedCommitOid(result.commitOid);
- commitsState.refresh();
- refreshBranchDiffAfterCommit(source, branchDiffState.refresh);
- if (pushAfterCommit) await runPushFlow();
- }, (messageText, err) => {
- if (!committed) return messageText;
- return decoratePushError(messageText, err);
- }).then((completed) => ({ committed, completed }));
- }, [branchDiffState, commitsState, decoratePushError, runPushFlow, runWrite, sessionId, setSelectedCommitOid, source, updateReviewDataFromWrite]);
+ const code = extractIpcError(err)?.code;
+ if (code === 'PUSH_LEASE_EXPIRED' || code === 'PUSH_NO_REMOTE' || code === 'SESSION_RUNNING')
+ return message;
+ return `${t('rightSidebar.review.push.failedTitle')}\n${message}`;
+ },
+ [t],
+ );
+
+ const commitChanges = useCallback(
+ (
+ message: string,
+ includeUnstaged: boolean,
+ pushAfterCommit: boolean,
+ ): Promise<ReviewCommitRunResult> => {
+ if (!sessionId) return Promise.resolve({ committed: false, completed: false });
+ let committed = false;
+ return runWrite(
+ pushAfterCommit ? 'commit-push' : 'commit',
+ async () => {
+ const result = await window.electronAPI.gitReview.commit({
+ sessionId,
+ message,
+ includeUnstaged,
+ });
+ committed = true;
+ updateReviewDataFromWrite(result.data);
+ if (source === 'commit') setDescriptor({ kind: 'commit', commitOid: result.commitOid });
+ commitsState.refresh();
+ if (source === 'branch') sourceState.refresh();
+ if (pushAfterCommit) await runPushFlow();
+ },
+ (messageText, err) => {
+ if (!committed) return messageText;
+ return decoratePushError(messageText, err);
+ },
+ ).then((completed) => ({ committed, completed }));
+ },
+ [
+ commitsState,
+ decoratePushError,
+ runPushFlow,
+ runWrite,
+ sessionId,
+ setDescriptor,
+ source,
+ sourceState,
+ updateReviewDataFromWrite,
+ ],
+ );
const pushCurrentBranch = useCallback(() => {
if (!sessionId) return;
@@ -1025,17 +1022,18 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
}, [decoratePushError, runPushFlow, runWrite, sessionId]);
useEffect(() => {
- if (shouldFallbackFromMissingSelectedCommit(
- source,
- selectedCommitOid,
- commits,
- commitsState.data !== null,
- commitsState.loading,
- )) {
- setSelectedCommitOid(null);
+ if (
+ shouldFallbackFromMissingSelectedCommit(
+ source,
+ selectedCommitOid,
+ commits,
+ commitsState.data !== null,
+ commitsState.loading,
+ )
+ ) {
setSource('branch');
}
- }, [commits, commitsState.data, commitsState.loading, selectedCommitOid, setSelectedCommitOid, setSource, source]);
+ }, [commits, commitsState.data, commitsState.loading, selectedCommitOid, setSource, source]);
const togglePath = useCallback(
(id: string) => {
@@ -1046,42 +1044,68 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
},
[collapsedSet, ctx, expandedSet],
);
- const setDiffViewMode = useCallback((mode: DiffViewMode) => {
- ctx.patchState({ diffViewMode: mode });
- }, [ctx]);
- const setFileTreeVisible = useCallback((visible: boolean) => {
- ctx.patchState({ fileTreeVisible: visible });
- }, [ctx]);
- const setWordWrap = useCallback((nextWordWrap: boolean) => {
- ctx.patchState({ wordWrap: nextWordWrap });
- }, [ctx]);
- const setWordDiff = useCallback((nextWordDiff: boolean) => {
- ctx.patchState({ wordDiff: nextWordDiff });
- }, [ctx]);
- const setHideWhitespace = useCallback((nextHideWhitespace: boolean) => {
- ctx.patchState({ hideWhitespace: nextHideWhitespace });
- }, [ctx]);
- const setRichMarkdownPreview = useCallback((nextRichMarkdownPreview: boolean) => {
- ctx.patchState({ richMarkdownPreview: nextRichMarkdownPreview });
- }, [ctx]);
- const setBranchBaseRef = useCallback((nextBaseRef: string) => {
- ctx.patchState({ branchBaseRef: nextBaseRef });
- }, [ctx]);
- const selectCommitSource = useCallback((oid: string) => {
- setSelectedCommitOid(oid);
- setSource('commit');
- }, [setSelectedCommitOid, setSource]);
+ const setDiffViewMode = useCallback(
+ (mode: DiffViewMode) => {
+ ctx.patchState({ diffViewMode: mode });
+ },
+ [ctx],
+ );
+ const setFileTreeVisible = useCallback(
+ (visible: boolean) => {
+ ctx.patchState({ fileTreeVisible: visible });
+ },
+ [ctx],
+ );
+ const setWordWrap = useCallback(
+ (nextWordWrap: boolean) => {
+ ctx.patchState({ wordWrap: nextWordWrap });
+ },
+ [ctx],
+ );
+ const setWordDiff = useCallback(
+ (nextWordDiff: boolean) => {
+ ctx.patchState({ wordDiff: nextWordDiff });
+ },
+ [ctx],
+ );
+ const setHideWhitespace = useCallback(
+ (nextHideWhitespace: boolean) => {
+ ctx.patchState({ hideWhitespace: nextHideWhitespace });
+ },
+ [ctx],
+ );
+ const setRichMarkdownPreview = useCallback(
+ (nextRichMarkdownPreview: boolean) => {
+ ctx.patchState({ richMarkdownPreview: nextRichMarkdownPreview });
+ },
+ [ctx],
+ );
+ const setBranchBaseRef = useCallback(
+ (nextBaseRef: string) => {
+ setDescriptor({ kind: 'branch', baseRef: nextBaseRef });
+ },
+ [setDescriptor],
+ );
+ const selectCommitSource = useCallback(
+ (oid: string) => {
+ setDescriptor({ kind: 'commit', commitOid: oid });
+ },
+ [setDescriptor],
+ );
const requestFileJump = useCallback((diff: FileDiff) => {
setJumpRequest((prev) => ({ id: diff.id, nonce: (prev?.nonce ?? 0) + 1 }));
}, []);
- 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) });
- }
- }, [collapsedSet, ctx]);
+ 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) });
+ }
+ },
+ [collapsedSet, ctx],
+ );
const toggleAllDiffs = useCallback(() => {
if (expansionToggle.action === 'disabled') return;
ctx.patchState({ collapsedPaths: expansionToggle.nextCollapsedPaths });
@@ -1089,7 +1113,8 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const copyGitApplyCommand = useCallback(() => {
const availability = getGitApplyCopyAvailability(visibleDiffs, hideWhitespace, platform);
if (!availability.canCopy) return;
- void navigator.clipboard.writeText(availability.payload.command)
+ void navigator.clipboard
+ .writeText(availability.payload.command)
.then(() => toast.success(t('rightSidebar.review.moreMenu.copyGitApplySuccess')))
.catch(() => toast.error(t('rightSidebar.review.moreMenu.copyGitApplyFailed')));
}, [hideWhitespace, platform, t, visibleDiffs]);
@@ -1129,14 +1154,26 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
}, [headerEl]);
if (!sessionId) {
- return <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.noSessionTitle')} desc={t('rightSidebar.review.noSessionDesc')} />;
+ return (
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.noSessionTitle')}
+ desc={t('rightSidebar.review.noSessionDesc')}
+ />
+ );
}
- if (!data && loading) {
- return <CenteredState icon={<Spinner icon={RefreshCw} size={24} />} title={t('rightSidebar.review.loadingTitle')} desc={t('rightSidebar.review.loadingDesc')} />;
+ if (source !== 'turn' && !data && sourceState.gitLoading) {
+ return (
+ <CenteredState
+ icon={<Spinner icon={RefreshCw} size={24} />}
+ title={t('rightSidebar.review.loadingTitle')}
+ desc={t('rightSidebar.review.loadingDesc')}
+ />
+ );
}
- if (error && !data) {
+ if (source !== 'turn' && sourceState.gitError && !data) {
// device-link 远程会话的两类确定性失败给专属占位:老被控端无 remote-op
// channel(升级即解决,刷新无用),以及响应超设备互联帧预算。
if (deviceLinkDeviceId && errorCode === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') {
@@ -1148,7 +1185,7 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
/>
);
}
- if (deviceLinkDeviceId && isReviewRemoteOversizeError(error)) {
+ if (deviceLinkDeviceId && isReviewRemoteOversizeError(sourceState.gitError)) {
return (
<CenteredState
icon={<AlertTriangle size={24} />}
@@ -1159,7 +1196,15 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
/>
);
}
- return <CenteredState icon={<AlertTriangle size={24} />} title={t('rightSidebar.review.errorTitle')} desc={error} actionLabel={t('rightSidebar.review.refresh')} onAction={refresh} />;
+ return (
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.errorTitle')}
+ desc={sourceState.gitError}
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={refresh}
+ />
+ );
}
if (data?.scope.disabledReason) {
@@ -1183,22 +1228,30 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
const branchLabel = data?.scope.isDetached
? t('rightSidebar.review.detachedHead', { oid: data.scope.headOid?.slice(0, 7) ?? '' })
: data?.scope.branch || t('rightSidebar.review.branchUnknown');
- const hasAnyDiff = rawUnstaged.length + rawStaged.length + sourceUnstagedCount + sourceStagedCount > 0;
- const reviewRefreshPending = loading || commitsState.loading || commitDiffState.loading || branchDiffState.loading || cappedFileDiffState.loading || lastTurnHydratedDiffState.loading;
+ const hasAnyDiff =
+ rawUnstaged.length + rawStaged.length + sourceUnstagedCount + sourceStagedCount > 0;
+ const reviewRefreshPending =
+ sourceState.loading ||
+ sourceState.gitLoading ||
+ commitsState.loading ||
+ cappedFileDiffState.loading;
const toolbarLayout = getReviewToolbarLayout(headerWidth);
const toolbarMinimal = toolbarLayout === 'minimal';
- const toolbarShowBranch = toolbarLayout === 'wide';
+ const toolbarShowBranch = toolbarLayout === 'wide' && capabilities.showBranchInfo;
const toolbarShowSecondaryActions = toolbarLayout !== 'minimal';
const toolbarFileTreeVisibility = getReviewFileTreeVisibility({
userVisible: fileTreeVisible,
containerWidth: headerWidth,
fileCount: visibleDiffs.length,
});
- const copyGitApplyDisabledTooltip = !gitApplyAvailability.canCopy
- ? gitApplyAvailability.reason === 'hide-whitespace'
- ? t('rightSidebar.review.moreMenu.copyGitApplyDisabledWhitespace')
- : t('rightSidebar.review.moreMenu.copyGitApplyDisabledEmpty')
- : undefined;
+ const copyGitApplyDisabledTooltip =
+ descriptor.kind === 'turn-set'
+ ? t('rightSidebar.review.turn.snapshotPatchUnavailable')
+ : !gitApplyAvailability.canCopy
+ ? gitApplyAvailability.reason === 'hide-whitespace'
+ ? t('rightSidebar.review.moreMenu.copyGitApplyDisabledWhitespace')
+ : t('rightSidebar.review.moreMenu.copyGitApplyDisabledEmpty')
+ : undefined;
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
@@ -1209,17 +1262,15 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
toolbarMinimal ? 'px-2' : 'px-3',
)}
>
- <div className={cn(
- 'flex min-h-8 min-w-0 items-center',
- toolbarMinimal ? 'gap-1' : 'gap-1.5',
- )}
+ <div
+ className={cn('flex min-h-8 min-w-0 items-center', toolbarMinimal ? 'gap-1' : 'gap-1.5')}
>
<SourceDropdown
source={source}
counts={{
unstaged: sourceUnstagedCount,
staged: sourceStagedCount,
- branch: branchDiffs.length,
+ branch: rawBranchDiffs.length,
lastTurn: sourceLastTurnCount,
}}
commits={commits}
@@ -1228,6 +1279,11 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
commitsLoaded={commitsState.data !== null}
selectedCommitOid={selectedCommitOid}
layout={toolbarLayout}
+ disabledReason={
+ capabilities.canSwitchSource
+ ? undefined
+ : t('rightSidebar.review.turn.crossSessionSwitchDisabled')
+ }
onChange={setSource}
onSelectCommit={selectCommitSource}
onRefreshCommits={commitsState.refresh}
@@ -1254,26 +1310,35 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
</div>
</>
)}
- <div className={cn(
- 'flex shrink-0 items-center',
- toolbarMinimal ? 'gap-0.5' : 'gap-1',
- !toolbarShowBranch && 'ml-auto',
- )}
+ <div
+ className={cn(
+ 'flex shrink-0 items-center',
+ toolbarMinimal ? 'gap-0.5' : 'gap-1',
+ !toolbarShowBranch && 'ml-auto',
+ )}
>
<ReviewMoreMenu
wordWrap={wordWrap}
wordDiff={wordDiff}
hideWhitespace={hideWhitespace}
- diffExpansionOverflow={toolbarShowSecondaryActions ? null : {
- action: expansionToggle.action,
- onToggle: toggleAllDiffs,
- }}
- fileTreeOverflow={toolbarShowSecondaryActions ? null : {
- preferenceVisible: fileTreeVisible,
- temporarilyHidden: toolbarFileTreeVisibility.temporarilyHidden,
- onToggle: () => setFileTreeVisible(!fileTreeVisible),
- }}
- canCopyGitApply={gitApplyAvailability.canCopy}
+ diffExpansionOverflow={
+ toolbarShowSecondaryActions
+ ? null
+ : {
+ action: expansionToggle.action,
+ onToggle: toggleAllDiffs,
+ }
+ }
+ fileTreeOverflow={
+ toolbarShowSecondaryActions
+ ? null
+ : {
+ preferenceVisible: fileTreeVisible,
+ temporarilyHidden: toolbarFileTreeVisibility.temporarilyHidden,
+ onToggle: () => setFileTreeVisible(!fileTreeVisible),
+ }
+ }
+ canCopyGitApply={descriptor.kind !== 'turn-set' && gitApplyAvailability.canCopy}
copyGitApplyDisabledTooltip={copyGitApplyDisabledTooltip}
onWordWrapChange={setWordWrap}
onWordDiffChange={setWordDiff}
@@ -1325,9 +1390,11 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
{effectiveWriteDisabledReasons.length > 0 && (
<div className="mt-2 flex items-start gap-2 rounded-[8px] border border-[var(--border-default)] bg-[var(--warning-bg-soft)] px-2.5 py-2 text-11 leading-relaxed text-[var(--text-secondary)]">
<AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" />
- <span>{t('rightSidebar.review.writeDisabledNotice', {
- reasons: writeDisabledReasonText,
- })}</span>
+ <span>
+ {t('rightSidebar.review.writeDisabledNotice', {
+ reasons: writeDisabledReasonText,
+ })}
+ </span>
</div>
)}
{(Boolean(operationError) || (operationSummary?.failed.length ?? 0) > 0) && (
@@ -1335,7 +1402,59 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
)}
</header>
- {currentCapped ? (
+ {!loading && !error && sourceState.isPartial && (
+ <div className="flex shrink-0 items-start gap-2 border-b border-[var(--border-default)] bg-[var(--warning-bg-soft)] px-3 py-2 text-11 leading-relaxed text-[var(--text-secondary)]">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" />
+ <span>{t('rightSidebar.review.turn.partialNotice')}</span>
+ </div>
+ )}
+
+ {source === 'turn' ? (
+ loading ? (
+ <CenteredState
+ icon={<Spinner size={24} />}
+ title={t('rightSidebar.review.loadingTitle')}
+ desc={t('rightSidebar.review.loadingDesc')}
+ />
+ ) : error ? (
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.errorTitle')}
+ desc={
+ error === REVIEW_TURN_LOCAL_ONLY_ERROR
+ ? t('rightSidebar.review.turn.localOnly')
+ : error
+ }
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={refreshAll}
+ />
+ ) : visibleDiffs.length === 0 ? (
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.turn.emptyTitle')}
+ desc={t('rightSidebar.review.turn.emptyDesc')}
+ />
+ ) : (
+ <DiffList
+ diffs={visibleDiffs}
+ expandedSet={expandedSet}
+ onToggleDiff={togglePath}
+ onRefresh={refreshAll}
+ refreshPending={reviewRefreshPending}
+ viewMode={diffViewMode}
+ onViewModeChange={setDiffViewMode}
+ onRichMarkdownPreviewChange={setRichMarkdownPreview}
+ wordWrap={wordWrap}
+ wordDiff={wordDiff}
+ fileTreeVisible={fileTreeVisible}
+ jumpRequest={resolvedJumpRequest}
+ loadImagePreview={unavailableHistoricalPreview}
+ loadMarkdownPreview={unavailableHistoricalPreview}
+ richMarkdownPreview={false}
+ richMarkdownPreviewDisabledReason={t('rightSidebar.review.turn.previewUnavailable')}
+ />
+ )
+ ) : currentCapped ? (
<CappedSourceView
capped={currentCapped}
summaryDiffs={cappedSummaryDiffs}
@@ -1346,61 +1465,77 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
onSelectFile={selectCappedFile}
onRefresh={refreshAll}
refreshPending={reviewRefreshPending}
- branchBaseControl={source === 'branch' ? (
- <BranchBaseDropdown
- candidates={branchCandidates}
- selectedBaseRef={selectedBranchBaseRef}
- onSelectBase={setBranchBaseRef}
- />
- ) : undefined}
- topNotice={source === 'branch' && currentBranchDiffData?.warning
- ? branchWarningText(currentBranchDiffData.warning, t)
- : null}
+ branchBaseControl={
+ source === 'branch' ? (
+ <BranchBaseDropdown
+ candidates={branchCandidates}
+ selectedBaseRef={selectedBranchBaseRef}
+ onSelectBase={setBranchBaseRef}
+ />
+ ) : undefined
+ }
+ topNotice={
+ source === 'branch' && currentBranchDiffData?.warning
+ ? branchWarningText(currentBranchDiffData.warning, t)
+ : null
+ }
viewMode={diffViewMode}
onViewModeChange={setDiffViewMode}
onRichMarkdownPreviewChange={setRichMarkdownPreview}
wordWrap={wordWrap}
wordDiff={wordDiff}
expandedSet={expandedSet}
- onToggleDiff={togglePath}
- fileTreeVisible
- loadImagePreview={loadImagePreview}
- loadMarkdownPreview={loadMarkdownPreview}
- richMarkdownPreview={richMarkdownPreview}
- onOpenFile={openFileHandler}
- writeAction={source === 'unstaged' ? {
- canWrite,
- pendingKey,
- disabledTooltip: actionWriteDisabledTooltip,
- actionForDiff: () => 'stage',
- discardForDiff: (diff) => diff.source === 'unstaged',
- hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
- sectionAction: null,
- sectionPendingKey: 'stage:all',
- onFileAction: (diff) => runStageOperation('stage', [targetFromDiff(diff)], `stage:file:${diff.id}`),
- onFileDiscard: runDiscardFileOperation,
- onHunkAction: (diff, hunkIndex) => runHunkOperation('stage', diff, hunkIndex),
- onHunkDiscard: runDiscardHunkOperation,
- } : source === 'staged' ? {
- canWrite,
- pendingKey,
- disabledTooltip: actionWriteDisabledTooltip,
- actionForDiff: () => 'unstage',
- hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
- sectionAction: null,
- sectionPendingKey: 'unstage:all',
- onFileAction: (diff) => runStageOperation('unstage', [targetFromDiff(diff)], `unstage:file:${diff.id}`),
- onHunkAction: (diff, hunkIndex) => runHunkOperation('unstage', diff, hunkIndex),
- } : undefined}
+ onToggleDiff={togglePath}
+ fileTreeVisible
+ loadImagePreview={loadImagePreview}
+ loadMarkdownPreview={loadMarkdownPreview}
+ richMarkdownPreview={capabilities.canRichPreview && richMarkdownPreview}
+ onOpenFile={openFileHandler}
+ writeAction={
+ source === 'unstaged'
+ ? {
+ canWrite,
+ pendingKey,
+ disabledTooltip: actionWriteDisabledTooltip,
+ actionForDiff: () => 'stage',
+ discardForDiff: (diff) => diff.source === 'unstaged',
+ hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
+ sectionAction: null,
+ sectionPendingKey: 'stage:all',
+ onFileAction: (diff) =>
+ runStageOperation('stage', [targetFromDiff(diff)], `stage:file:${diff.id}`),
+ onFileDiscard: runDiscardFileOperation,
+ onHunkAction: (diff, hunkIndex) => runHunkOperation('stage', diff, hunkIndex),
+ onHunkDiscard: runDiscardHunkOperation,
+ }
+ : source === 'staged'
+ ? {
+ canWrite,
+ pendingKey,
+ disabledTooltip: actionWriteDisabledTooltip,
+ actionForDiff: () => 'unstage',
+ hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
+ sectionAction: null,
+ sectionPendingKey: 'unstage:all',
+ onFileAction: (diff) =>
+ runStageOperation(
+ 'unstage',
+ [targetFromDiff(diff)],
+ `unstage:file:${diff.id}`,
+ ),
+ onHunkAction: (diff, hunkIndex) => runHunkOperation('unstage', diff, hunkIndex),
+ }
+ : undefined
+ }
/>
) : source === 'commit' ? (
<CommitSourceView
selectedCommitOid={effectiveCommitOid}
- diffs={commitDiffs}
+ diffs={sourceState.diffs}
rawDiffCount={rawCommitDiffs.length}
- diffLoading={commitDiffState.loading && !selectedCommitDiff}
- diffError={localizeReviewError(commitDiffState.error)}
- onRefreshDiff={commitDiffState.refresh}
+ diffLoading={sourceState.loading && !selectedCommitDiff}
+ diffError={localizeReviewError(sourceState.error)}
+ onRefreshDiff={sourceState.refresh}
onRefresh={refreshAll}
refreshPending={reviewRefreshPending}
expandedSet={expandedSet}
@@ -1411,10 +1546,10 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
wordWrap={wordWrap}
wordDiff={wordDiff}
fileTreeVisible={fileTreeVisible}
- jumpRequest={jumpRequest}
+ jumpRequest={resolvedJumpRequest}
loadImagePreview={loadImagePreview}
loadMarkdownPreview={loadMarkdownPreview}
- richMarkdownPreview={richMarkdownPreview}
+ richMarkdownPreview={capabilities.canRichPreview && richMarkdownPreview}
onOpenFile={openFileHandler}
/>
) : source === 'branch' ? (
@@ -1422,12 +1557,12 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
candidates={branchCandidates}
selectedBaseRef={selectedBranchBaseRef}
warning={currentBranchDiffData?.warning ?? null}
- diffs={branchDiffs}
+ diffs={sourceState.diffs}
rawDiffCount={rawBranchDiffs.length}
- diffLoading={branchDiffState.loading && !currentBranchDiffData}
- diffError={localizeReviewError(branchDiffState.error)}
+ diffLoading={sourceState.loading && !currentBranchDiffData}
+ diffError={localizeReviewError(sourceState.error)}
onSelectBase={setBranchBaseRef}
- onRefreshDiff={branchDiffState.refresh}
+ onRefreshDiff={sourceState.refresh}
onRefresh={refreshAll}
refreshPending={reviewRefreshPending}
expandedSet={expandedSet}
@@ -1438,10 +1573,10 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
wordWrap={wordWrap}
wordDiff={wordDiff}
fileTreeVisible={fileTreeVisible}
- jumpRequest={jumpRequest}
+ jumpRequest={resolvedJumpRequest}
loadImagePreview={loadImagePreview}
loadMarkdownPreview={loadMarkdownPreview}
- richMarkdownPreview={richMarkdownPreview}
+ richMarkdownPreview={capabilities.canRichPreview && richMarkdownPreview}
onOpenFile={openFileHandler}
/>
) : source === 'staged' ? (
@@ -1455,19 +1590,23 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
canWrite={canWrite}
pendingKey={pendingKey}
actionDisabledTooltip={actionWriteDisabledTooltip}
- onFileAction={(diff) => runStageOperation('unstage', [targetFromDiff(diff)], `unstage:file:${diff.id}`)}
+ onFileAction={(diff) =>
+ runStageOperation('unstage', [targetFromDiff(diff)], `unstage:file:${diff.id}`)
+ }
onHunkAction={(diff, hunkIndex) => runHunkOperation('unstage', diff, hunkIndex)}
- onSectionAction={() => runStageOperation('unstage', staged.map(targetFromDiff), 'unstage:all')}
+ onSectionAction={() =>
+ runStageOperation('unstage', staged.map(targetFromDiff), 'unstage:all')
+ }
viewMode={diffViewMode}
onViewModeChange={setDiffViewMode}
onRichMarkdownPreviewChange={setRichMarkdownPreview}
wordWrap={wordWrap}
wordDiff={wordDiff}
fileTreeVisible={fileTreeVisible}
- jumpRequest={jumpRequest}
+ jumpRequest={resolvedJumpRequest}
loadImagePreview={loadImagePreview}
loadMarkdownPreview={loadMarkdownPreview}
- richMarkdownPreview={richMarkdownPreview}
+ richMarkdownPreview={capabilities.canRichPreview && richMarkdownPreview}
onOpenFile={openFileHandler}
hunkActionsEnabled={canUsePatchBasedReviewActions(hideWhitespace)}
/>
@@ -1485,7 +1624,7 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
actionLabel={t('rightSidebar.review.refresh')}
onAction={refreshAll}
/>
- ) : source === 'last-turn' && rawLastTurnDiffs.length === 0 ? (
+ ) : source === 'last-turn' && sourceState.rawDiffCount === 0 ? (
<CenteredState
icon={<FileDiffIcon size={24} />}
title={t('rightSidebar.review.lastTurnEmpty.title')}
@@ -1494,9 +1633,17 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
onAction={() => setSource('branch')}
/>
) : !hasAnyDiff ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.emptyTitle')} desc={t('rightSidebar.review.emptyDescGit')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.emptyTitle')}
+ desc={t('rightSidebar.review.emptyDescGit')}
+ />
) : visibleDiffs.length === 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.filterEmptyTitle')} desc={t('rightSidebar.review.filterEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.filterEmptyTitle')}
+ desc={t('rightSidebar.review.filterEmptyDesc')}
+ />
) : (
<DiffList
diffs={visibleDiffs}
@@ -1510,41 +1657,48 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
wordWrap={wordWrap}
wordDiff={wordDiff}
fileTreeVisible={fileTreeVisible}
- jumpRequest={jumpRequest}
+ jumpRequest={resolvedJumpRequest}
loadImagePreview={loadImagePreview}
loadMarkdownPreview={loadMarkdownPreview}
- richMarkdownPreview={richMarkdownPreview}
+ richMarkdownPreview={capabilities.canRichPreview && richMarkdownPreview}
onOpenFile={openFileHandler}
- writeAction={source === 'last-turn' ? undefined : {
- canWrite,
- pendingKey,
- disabledTooltip: actionWriteDisabledTooltip,
- actionForDiff: (diff) => actionForReviewDiff(source, diff),
- discardForDiff: (diff) => discardForReviewDiff(source, diff),
- hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
- sectionAction: source === 'unstaged' ? 'stage' : null,
- sectionPendingKey: 'stage:all',
- sectionDiscardVisible: source === 'unstaged',
- sectionDiscardPendingKey: 'discard:all',
- onFileAction: (diff) => {
- const action = actionForReviewDiff(source, diff);
- if (!action) return;
- runStageOperation(action, [targetFromDiff(diff)], `${action}:file:${diff.id}`);
- },
- onFileDiscard: runDiscardFileOperation,
- onHunkAction: (diff, hunkIndex) => {
- const action = actionForReviewDiff(source, diff);
- if (!action) return;
- runHunkOperation(action, diff, hunkIndex);
- },
- onHunkDiscard: runDiscardHunkOperation,
- onSectionAction: source === 'unstaged'
- ? () => runStageOperation('stage', visibleDiffs.map(targetFromDiff), 'stage:all')
- : undefined,
- onSectionDiscard: source === 'unstaged'
- ? () => runDiscardSectionOperation(visibleDiffs, 'discard:all')
- : undefined,
- }}
+ writeAction={
+ source === 'last-turn'
+ ? undefined
+ : {
+ canWrite,
+ pendingKey,
+ disabledTooltip: actionWriteDisabledTooltip,
+ actionForDiff: (diff) => actionForReviewDiff(source, diff),
+ discardForDiff: (diff) => discardForReviewDiff(source, diff),
+ hunkActionsEnabled: canUsePatchBasedReviewActions(hideWhitespace),
+ sectionAction: source === 'unstaged' ? 'stage' : null,
+ sectionPendingKey: 'stage:all',
+ sectionDiscardVisible: source === 'unstaged',
+ sectionDiscardPendingKey: 'discard:all',
+ onFileAction: (diff) => {
+ const action = actionForReviewDiff(source, diff);
+ if (!action) return;
+ runStageOperation(action, [targetFromDiff(diff)], `${action}:file:${diff.id}`);
+ },
+ onFileDiscard: runDiscardFileOperation,
+ onHunkAction: (diff, hunkIndex) => {
+ const action = actionForReviewDiff(source, diff);
+ if (!action) return;
+ runHunkOperation(action, diff, hunkIndex);
+ },
+ onHunkDiscard: runDiscardHunkOperation,
+ onSectionAction:
+ source === 'unstaged'
+ ? () =>
+ runStageOperation('stage', visibleDiffs.map(targetFromDiff), 'stage:all')
+ : undefined,
+ onSectionDiscard:
+ source === 'unstaged'
+ ? () => runDiscardSectionOperation(visibleDiffs, 'discard:all')
+ : undefined,
+ }
+ }
/>
)}
</div>
@@ -1601,13 +1755,14 @@ function getPushControlState({
const disabledReason = !branch
? t('rightSidebar.review.push.disabledNoBranch')
: !canWrite && !pending
- ? writeDisabledText ?? t('rightSidebar.review.push.disabledWriteGate')
+ ? (writeDisabledText ?? t('rightSidebar.review.push.disabledWriteGate'))
: synced
? t('rightSidebar.review.push.synced')
: strictlyBehind
? t('rightSidebar.review.push.disabledBehindOnly', { count: behind })
: null;
- const tooltip = disabledReason ??
+ const tooltip =
+ disabledReason ??
(upstream
? behind > 0
? t('rightSidebar.review.push.readyForceCandidate', { count: behind })
@@ -1645,7 +1800,11 @@ function CommitOrPushDropdown({
push: PushControlProps;
iconOnly?: boolean;
platform: string;
- onCommit: (message: string, includeUnstaged: boolean, pushAfterCommit: boolean) => Promise<ReviewCommitRunResult>;
+ onCommit: (
+ message: string,
+ includeUnstaged: boolean,
+ pushAfterCommit: boolean,
+ ) => Promise<ReviewCommitRunResult>;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -1653,10 +1812,14 @@ function CommitOrPushDropdown({
const [includeUnstaged, setIncludeUnstaged] = useState(false);
const inputRef = useRef<HTMLTextAreaElement | null>(null);
const writeDisabledTooltip = writeDisabledText
- ? t('rightSidebar.review.topAction.disabledWriteGateWithReasons', { reasons: writeDisabledText })
+ ? t('rightSidebar.review.topAction.disabledWriteGateWithReasons', {
+ reasons: writeDisabledText,
+ })
: t('rightSidebar.review.topAction.disabledWriteGate');
const triggerDisabled = (!canWrite && !pending) || pending;
- const triggerTooltip = !canWrite ? writeDisabledTooltip : t('rightSidebar.review.topAction.label');
+ const triggerTooltip = !canWrite
+ ? writeDisabledTooltip
+ : t('rightSidebar.review.topAction.label');
const commitDisabledReason = getReviewCommitActionDisabledReason({
message,
includeUnstaged,
@@ -1664,47 +1827,58 @@ function CommitOrPushDropdown({
unstagedCount,
canWrite,
});
- const commitDisabledTooltip = commitDisabledReason === 'no-message'
- ? t('rightSidebar.review.commit.disabledNoMessage')
- : commitDisabledReason === 'write-disabled'
- ? writeDisabledTooltip
- : commitDisabledReason === 'no-changes'
- ? t('rightSidebar.review.commit.disabledNoChanges')
- : commitDisabledReason === 'no-staged'
- ? t('rightSidebar.review.commit.disabledNoStaged')
- : undefined;
+ const commitDisabledTooltip =
+ commitDisabledReason === 'no-message'
+ ? t('rightSidebar.review.commit.disabledNoMessage')
+ : commitDisabledReason === 'write-disabled'
+ ? writeDisabledTooltip
+ : commitDisabledReason === 'no-changes'
+ ? t('rightSidebar.review.commit.disabledNoChanges')
+ : commitDisabledReason === 'no-staged'
+ ? t('rightSidebar.review.commit.disabledNoStaged')
+ : undefined;
const commitDisabled = pending || Boolean(commitDisabledReason);
const pushState = getPushControlState({ ...push, t });
const shortcut = platform === 'darwin' ? '⌘↩' : 'Ctrl↩';
- const runCommit = useCallback((pushAfterCommit: boolean) => {
- if (commitDisabled) return;
- void onCommit(message, includeUnstaged, pushAfterCommit).then((result) => {
- const effect = getReviewCommitDropdownCompletionEffect(result);
- if (effect.clearMessage) setMessage('');
- if (effect.closeDropdown) setOpen(false);
- });
- }, [commitDisabled, includeUnstaged, message, onCommit]);
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- const shortcutPressed = platform === 'darwin'
- ? event.metaKey && event.key === 'Enter'
- : event.ctrlKey && event.key === 'Enter';
- if (!shortcutPressed) return;
- event.preventDefault();
- runCommit(false);
- }, [platform, runCommit]);
+ const runCommit = useCallback(
+ (pushAfterCommit: boolean) => {
+ if (commitDisabled) return;
+ void onCommit(message, includeUnstaged, pushAfterCommit).then((result) => {
+ const effect = getReviewCommitDropdownCompletionEffect(result);
+ if (effect.clearMessage) setMessage('');
+ if (effect.closeDropdown) setOpen(false);
+ });
+ },
+ [commitDisabled, includeUnstaged, message, onCommit],
+ );
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ const shortcutPressed =
+ platform === 'darwin'
+ ? event.metaKey && event.key === 'Enter'
+ : event.ctrlKey && event.key === 'Enter';
+ if (!shortcutPressed) return;
+ event.preventDefault();
+ runCommit(false);
+ },
+ [platform, runCommit],
+ );
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() => inputRef.current?.focus());
return () => cancelAnimationFrame(frame);
}, [open]);
return (
- <DropdownMenu open={open} onOpenChange={(nextOpen) => {
- if (triggerDisabled) {
- setOpen(false);
- return;
- }
- setOpen(nextOpen);
- }}>
+ <DropdownMenu
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (triggerDisabled) {
+ setOpen(false);
+ return;
+ }
+ setOpen(nextOpen);
+ }}
+ >
<DropdownMenuTrigger asChild>
<Tip text={triggerTooltip}>
<button
@@ -1721,7 +1895,9 @@ function CommitOrPushDropdown({
)}
>
{pending ? <Spinner size={12} /> : <Check size={12} />}
- <span className={cn(iconOnly && 'sr-only')}>{t('rightSidebar.review.topAction.label')}</span>
+ <span className={cn(iconOnly && 'sr-only')}>
+ {t('rightSidebar.review.topAction.label')}
+ </span>
</button>
</Tip>
</DropdownMenuTrigger>
@@ -1734,7 +1910,9 @@ function CommitOrPushDropdown({
>
<div className="flex min-w-0 items-center gap-2 rounded-[8px] bg-[var(--surface-chip)] px-2.5 py-2 text-12">
<GitBranch size={13} className="shrink-0 text-[var(--text-tertiary)]" />
- <span className="min-w-0 flex-1 truncate font-medium text-[var(--text-primary)]">{branchLabel}</span>
+ <span className="min-w-0 flex-1 truncate font-medium text-[var(--text-primary)]">
+ {branchLabel}
+ </span>
<span className="shrink-0 whitespace-nowrap font-mono text-11 tabular-nums">
<span className="text-[var(--diff-add-fg)]">+{totalAdd}</span>{' '}
<span className="text-[var(--diff-del-fg)]">-{totalDel}</span>
@@ -1764,7 +1942,9 @@ function CommitOrPushDropdown({
<span className="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-[3px] border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)]">
{includeUnstaged && <Check size={10} />}
</span>
- <span className="min-w-0 flex-1 truncate">{t('rightSidebar.review.commit.includeUnstaged')}</span>
+ <span className="min-w-0 flex-1 truncate">
+ {t('rightSidebar.review.commit.includeUnstaged')}
+ </span>
</DropdownMenuItem>
<DropdownMenuSeparator className="my-1 bg-[var(--border-default)]" />
<CommitDropdownAction
@@ -1836,7 +2016,9 @@ function CommitDropdownAction({
disabled && 'cursor-not-allowed opacity-50',
)}
>
- <span className="flex h-3 w-3 shrink-0 items-center justify-center text-[var(--text-secondary)]">{icon}</span>
+ <span className="flex h-3 w-3 shrink-0 items-center justify-center text-[var(--text-secondary)]">
+ {icon}
+ </span>
<span className="min-w-0 flex-1 truncate">{label}</span>
{children}
{shortcut && (
@@ -1877,48 +2059,63 @@ function FileJumpPopover({
}, [query, results.length]);
const close = useCallback(() => setOpen(false), []);
- const selectResult = useCallback((result: ReviewFileJumpResult | null | undefined) => {
- if (!result) return;
- onSelectFile(result.diff);
- close();
- }, [close, onSelectFile]);
- const handleOpenChange = useCallback((nextOpen: boolean) => {
- if (disabled) {
- setOpen(false);
- return;
- }
- if (nextOpen) {
- setQuery('');
- setSelectedIndex(diffs.length > 0 ? 0 : -1);
- }
- setOpen(nextOpen);
- }, [diffs.length, disabled]);
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- if (event.key === 'ArrowDown') {
- event.preventDefault();
- setSelectedIndex((current) => moveReviewFileJumpSelection(current, 1, results.length));
- return;
- }
- if (event.key === 'ArrowUp') {
- event.preventDefault();
- setSelectedIndex((current) => moveReviewFileJumpSelection(current, -1, results.length));
- return;
- }
- if (event.key === 'Enter') {
- event.preventDefault();
- selectResult(results[selectedIndex]);
- return;
- }
- if (event.key === 'Escape') {
- event.preventDefault();
+ const selectResult = useCallback(
+ (result: ReviewFileJumpResult | null | undefined) => {
+ if (!result) return;
+ onSelectFile(result.diff);
close();
- }
- }, [close, results, selectResult, selectedIndex]);
+ },
+ [close, onSelectFile],
+ );
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (disabled) {
+ setOpen(false);
+ return;
+ }
+ if (nextOpen) {
+ setQuery('');
+ setSelectedIndex(diffs.length > 0 ? 0 : -1);
+ }
+ setOpen(nextOpen);
+ },
+ [diffs.length, disabled],
+ );
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ setSelectedIndex((current) => moveReviewFileJumpSelection(current, 1, results.length));
+ return;
+ }
+ if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ setSelectedIndex((current) => moveReviewFileJumpSelection(current, -1, results.length));
+ return;
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ selectResult(results[selectedIndex]);
+ return;
+ }
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ close();
+ }
+ },
+ [close, results, selectResult, selectedIndex],
+ );
return (
<Popover open={open && !disabled} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
- <Tip text={disabled ? t('rightSidebar.review.fileJump.disabled') : t('rightSidebar.review.fileJump.tooltip')}>
+ <Tip
+ text={
+ disabled
+ ? t('rightSidebar.review.fileJump.disabled')
+ : t('rightSidebar.review.fileJump.tooltip')
+ }
+ >
<button
type="button"
disabled={disabled}
@@ -1944,7 +2141,10 @@ function FileJumpPopover({
>
<div onKeyDown={handleKeyDown}>
<label className="relative block">
- <Search size={12} className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]" />
+ <Search
+ size={12}
+ className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]"
+ />
<input
ref={inputRef}
value={query}
@@ -2042,11 +2242,12 @@ function FileTreeToggleButton({
onToggle: () => void;
}) {
const { t } = useTranslation();
- const label = preferenceVisible && temporarilyHidden
- ? t('rightSidebar.review.fileTree.temporarilyHidden')
- : preferenceVisible
- ? t('rightSidebar.review.fileTree.hide')
- : t('rightSidebar.review.fileTree.show');
+ const label =
+ preferenceVisible && temporarilyHidden
+ ? t('rightSidebar.review.fileTree.temporarilyHidden')
+ : preferenceVisible
+ ? t('rightSidebar.review.fileTree.hide')
+ : t('rightSidebar.review.fileTree.show');
return (
<Tip text={label}>
<button
@@ -2165,31 +2366,57 @@ export function ReviewMoreMenu({
onSelect={() => onWordWrapChange(!wordWrap)}
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)]"
>
- {wordWrap
- ? <WrapText size={12} className="text-[var(--text-secondary)]" />
- : <ArrowRight size={12} className="text-[var(--text-secondary)]" />}
- <span>{t(wordWrap ? 'rightSidebar.review.moreMenu.wordWrapDisable' : 'rightSidebar.review.moreMenu.wordWrapEnable')}</span>
+ {wordWrap ? (
+ <WrapText size={12} className="text-[var(--text-secondary)]" />
+ ) : (
+ <ArrowRight size={12} className="text-[var(--text-secondary)]" />
+ )}
+ <span>
+ {t(
+ wordWrap
+ ? 'rightSidebar.review.moreMenu.wordWrapDisable'
+ : 'rightSidebar.review.moreMenu.wordWrapEnable',
+ )}
+ </span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onWordDiffChange(!wordDiff)}
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)]"
>
- {wordDiff
- ? <Diff size={12} className="text-[var(--text-secondary)]" />
- : <SquareSplitHorizontal size={12} className="text-[var(--text-secondary)]" />}
- <span>{t(wordDiff ? 'rightSidebar.review.moreMenu.wordDiffDisable' : 'rightSidebar.review.moreMenu.wordDiffEnable')}</span>
+ {wordDiff ? (
+ <Diff size={12} className="text-[var(--text-secondary)]" />
+ ) : (
+ <SquareSplitHorizontal size={12} className="text-[var(--text-secondary)]" />
+ )}
+ <span>
+ {t(
+ wordDiff
+ ? 'rightSidebar.review.moreMenu.wordDiffDisable'
+ : 'rightSidebar.review.moreMenu.wordDiffEnable',
+ )}
+ </span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onHideWhitespaceChange(!hideWhitespace)}
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)]"
>
- {hideWhitespace
- ? <EyeOff size={12} className="text-[var(--text-secondary)]" />
- : <Eye size={12} className="text-[var(--text-secondary)]" />}
- <span>{t(hideWhitespace ? 'rightSidebar.review.moreMenu.showWhitespace' : 'rightSidebar.review.moreMenu.hideWhitespace')}</span>
+ {hideWhitespace ? (
+ <EyeOff size={12} className="text-[var(--text-secondary)]" />
+ ) : (
+ <Eye size={12} className="text-[var(--text-secondary)]" />
+ )}
+ <span>
+ {t(
+ hideWhitespace
+ ? 'rightSidebar.review.moreMenu.showWhitespace'
+ : 'rightSidebar.review.moreMenu.hideWhitespace',
+ )}
+ </span>
</DropdownMenuItem>
<DropdownMenuSeparator className="my-1 bg-[var(--border-default)]" />
- {canCopyGitApply || !copyGitApplyDisabledTooltip ? copyItem : (
+ {canCopyGitApply || !copyGitApplyDisabledTooltip ? (
+ copyItem
+ ) : (
<Tip text={copyGitApplyDisabledTooltip}>
<span className="block">{copyItem}</span>
</Tip>
@@ -2199,10 +2426,7 @@ export function ReviewMoreMenu({
);
}
-function DiffExpansionMenuItem({
- action,
- onToggle,
-}: DiffExpansionOverflowProps) {
+function DiffExpansionMenuItem({ action, onToggle }: DiffExpansionOverflowProps) {
const { t } = useTranslation();
const disabled = action === 'disabled';
const label = disabled
@@ -2225,9 +2449,11 @@ function DiffExpansionMenuItem({
disabled && 'cursor-not-allowed opacity-50',
)}
>
- {action === 'collapse'
- ? <UnfoldVertical size={12} className="text-[var(--text-secondary)]" />
- : <FoldVertical size={12} className="text-[var(--text-secondary)]" />}
+ {action === 'collapse' ? (
+ <UnfoldVertical size={12} className="text-[var(--text-secondary)]" />
+ ) : (
+ <FoldVertical size={12} className="text-[var(--text-secondary)]" />
+ )}
<span className="min-w-0 truncate">{label}</span>
</DropdownMenuItem>
);
@@ -2235,7 +2461,9 @@ function DiffExpansionMenuItem({
<Tip text={label}>
<span className="block">{item}</span>
</Tip>
- ) : item;
+ ) : (
+ item
+ );
}
function FileTreeMenuItem({
@@ -2244,19 +2472,22 @@ function FileTreeMenuItem({
onToggle,
}: FileTreeOverflowProps) {
const { t } = useTranslation();
- const label = preferenceVisible && temporarilyHidden
- ? t('rightSidebar.review.fileTree.temporarilyHidden')
- : preferenceVisible
- ? t('rightSidebar.review.fileTree.hide')
- : t('rightSidebar.review.fileTree.show');
+ const label =
+ preferenceVisible && temporarilyHidden
+ ? t('rightSidebar.review.fileTree.temporarilyHidden')
+ : preferenceVisible
+ ? t('rightSidebar.review.fileTree.hide')
+ : t('rightSidebar.review.fileTree.show');
return (
<DropdownMenuItem
onSelect={onToggle}
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)]"
>
- {preferenceVisible
- ? <FolderOpen size={12} className="text-[var(--text-secondary)]" />
- : <Folder size={12} className="text-[var(--text-secondary)]" />}
+ {preferenceVisible ? (
+ <FolderOpen size={12} className="text-[var(--text-secondary)]" />
+ ) : (
+ <Folder size={12} className="text-[var(--text-secondary)]" />
+ )}
<span className="min-w-0 truncate">{label}</span>
</DropdownMenuItem>
);
@@ -2271,11 +2502,12 @@ export function SourceDropdown({
commitsLoaded,
selectedCommitOid,
layout = 'wide',
+ disabledReason,
onChange,
onSelectCommit,
onRefreshCommits,
}: {
- /** `'turn'` 表示轮次审查(turnTarget)选中态:非 git 来源,仅作为当前项展示。 */
+ /** `'turn'` is the selected label for a persisted turn-set descriptor. */
source: ReviewSource | 'turn';
counts: { unstaged?: number; staged?: number; branch?: number; lastTurn?: number };
commits?: ReviewCommit[];
@@ -2284,16 +2516,17 @@ export function SourceDropdown({
commitsLoaded?: boolean;
selectedCommitOid?: string | null;
layout?: ReviewToolbarLayout;
+ disabledReason?: string;
onChange: (source: ReviewSource) => void;
onSelectCommit?: (oid: string) => void;
onRefreshCommits?: () => void;
}) {
const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
// 轮次项只在轮次审查态存在(进入它的唯一入口是聊天流的变更卡片);
- // 切走即清 turnTarget、不提供"切回轮次"的常驻项,对齐 Codex 的 EP 语义。
- const turnOption: SourceDropdownOption | null = source === 'turn'
- ? { source: 'turn', label: t('rightSidebar.review.turn.title') }
- : null;
+ // 切走即整体替换 descriptor,不提供"切回轮次"的常驻项。
+ const turnOption: SourceDropdownOption | null =
+ source === 'turn' ? { 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 },
@@ -2306,33 +2539,40 @@ export function SourceDropdown({
const commitList = commits ?? [];
const commitMenuLoaded = commitsLoaded ?? false;
return (
- <DropdownMenu>
+ <DropdownMenu
+ open={open}
+ onOpenChange={(nextOpen) => setOpen(disabledReason ? false : nextOpen)}
+ >
<DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={t('rightSidebar.review.sourceDropdownAria')}
- className={cn(
- 'flex h-7 shrink-0 items-center justify-between rounded-full border border-transparent bg-transparent px-1.5 text-left text-12 font-medium text-[var(--text-primary)] hover:bg-[var(--surface-hover)]',
- layout === 'wide' ? 'max-w-[11rem]' : 'max-w-[10rem]',
- )}
- >
- <span className="truncate">{selected.label}</span>
- <SourceCountBadge count={selected.count} />
- <ChevronDown size={13} className={cn('shrink-0 text-[var(--text-tertiary)]', layout === 'minimal' ? 'ml-1' : 'ml-2')} />
- </button>
+ <Tip text={disabledReason ?? t('rightSidebar.review.sourceDropdownAria')}>
+ <button
+ type="button"
+ aria-disabled={Boolean(disabledReason)}
+ aria-label={t('rightSidebar.review.sourceDropdownAria')}
+ className={cn(
+ 'flex h-7 shrink-0 items-center justify-between rounded-full border border-transparent bg-transparent px-1.5 text-left text-12 font-medium text-[var(--text-primary)] hover:bg-[var(--surface-hover)]',
+ layout === 'wide' ? 'max-w-[11rem]' : 'max-w-[10rem]',
+ disabledReason && 'cursor-not-allowed opacity-50 hover:bg-transparent',
+ )}
+ >
+ <span className="truncate">{selected.label}</span>
+ <SourceCountBadge count={selected.count} />
+ <ChevronDown
+ size={13}
+ className={cn(
+ 'shrink-0 text-[var(--text-tertiary)]',
+ layout === 'minimal' ? 'ml-1' : 'ml-2',
+ )}
+ />
+ </button>
+ </Tip>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
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 onChange={onChange} />}
{directOptions.slice(0, 2).map((option) => (
<SourceDropdownItem
key={option.source}
@@ -2341,12 +2581,15 @@ export function SourceDropdown({
onChange={onChange}
/>
))}
- <DropdownMenuSub onOpenChange={(open) => {
- if (open) onRefreshCommits?.();
- }}
+ <DropdownMenuSub
+ onOpenChange={(open) => {
+ if (open) onRefreshCommits?.();
+ }}
>
<DropdownMenuSubTrigger 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)] data-[state=open]:bg-[var(--cmd-palette-item-hover)]">
- <span className="min-w-0 flex-1 truncate">{t('rightSidebar.review.source.commit')}</span>
+ <span className="min-w-0 flex-1 truncate">
+ {t('rightSidebar.review.source.commit')}
+ </span>
<span className="flex h-4 w-4 shrink-0 items-center justify-center text-[var(--text-secondary)]">
{source === 'commit' && <Check size={12} />}
</span>
@@ -2373,7 +2616,12 @@ export function SourceDropdown({
}}
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)]"
>
- <Spinner icon={RefreshCw} size={12} spinning={commitsLoading} className="text-[var(--text-secondary)]" />
+ <Spinner
+ icon={RefreshCw}
+ size={12}
+ spinning={commitsLoading}
+ className="text-[var(--text-secondary)]"
+ />
<span>{t('rightSidebar.review.commitMenu.retry')}</span>
</DropdownMenuItem>
</>
@@ -2393,31 +2641,36 @@ export function SourceDropdown({
<FileDiffIcon size={12} />
<span>{t('rightSidebar.review.commitMenu.empty')}</span>
</DropdownMenuItem>
- ) : commitList.map((commit) => {
- const title = commit.title || t('rightSidebar.review.untitledCommit');
- const active = commit.oid === selectedCommitOid;
- return (
- <Tip key={commit.oid} text={title} side="left">
- <DropdownMenuItem
- onSelect={() => onSelectCommit?.(commit.oid)}
- className={cn(
- 'flex h-8 min-w-0 items-center gap-2 rounded-[6px] px-2 text-12 text-[var(--text-primary)] focus:bg-[var(--cmd-palette-item-hover)]',
- active && 'bg-[var(--surface-chip)]',
- )}
- >
- <span className="min-w-0 flex-1 truncate">{title}</span>
- <span className="shrink-0 text-10 text-[var(--text-tertiary)]">
- {t('rightSidebar.review.commitMenu.relativeTime', {
- time: formatSidebarTime(new Date(commit.authorTime * 1000).toISOString(), t),
- })}
- </span>
- <span className="flex h-4 w-4 shrink-0 items-center justify-center text-[var(--text-secondary)]">
- {active && <Check size={12} />}
- </span>
- </DropdownMenuItem>
- </Tip>
- );
- })}
+ ) : (
+ commitList.map((commit) => {
+ const title = commit.title || t('rightSidebar.review.untitledCommit');
+ const active = commit.oid === selectedCommitOid;
+ return (
+ <Tip key={commit.oid} text={title} side="left">
+ <DropdownMenuItem
+ onSelect={() => onSelectCommit?.(commit.oid)}
+ className={cn(
+ 'flex h-8 min-w-0 items-center gap-2 rounded-[6px] px-2 text-12 text-[var(--text-primary)] focus:bg-[var(--cmd-palette-item-hover)]',
+ active && 'bg-[var(--surface-chip)]',
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate">{title}</span>
+ <span className="shrink-0 text-10 text-[var(--text-tertiary)]">
+ {t('rightSidebar.review.commitMenu.relativeTime', {
+ time: formatSidebarTime(
+ new Date(commit.authorTime * 1000).toISOString(),
+ t,
+ ),
+ })}
+ </span>
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-[var(--text-secondary)]">
+ {active && <Check size={12} />}
+ </span>
+ </DropdownMenuItem>
+ </Tip>
+ );
+ })
+ )}
</DropdownMenuSubContent>
</DropdownMenuSub>
{directOptions.slice(2).map((option) => (
@@ -2483,14 +2736,16 @@ function targetFromDiff(diff: FileDiff): ReviewFileTarget {
}
export function partialAllowed(diff: FileDiff): boolean {
- return diff.kind === 'text' &&
+ return (
+ diff.kind === 'text' &&
!diff.isBinary &&
!diff.isSubmodule &&
diff.status !== 'renamed' &&
diff.status !== 'copied' &&
diff.status !== 'deleted' &&
diff.status !== 'typechange' &&
- !isTypechangeModeChange(diff);
+ !isTypechangeModeChange(diff)
+ );
}
function isRenameLikeDiff(diff: FileDiff): boolean {
@@ -2512,25 +2767,37 @@ function isTypechangeModeChange(diff: FileDiff): boolean {
}
function actionLabel(action: ReviewToggleAction, t: (key: string) => string): string {
- return action === 'stage' ? t('rightSidebar.review.actions.stage') : t('rightSidebar.review.actions.unstage');
+ return action === 'stage'
+ ? t('rightSidebar.review.actions.stage')
+ : t('rightSidebar.review.actions.unstage');
}
function hunkActionLabel(action: ReviewToggleAction, t: (key: string) => string): string {
- return action === 'stage' ? t('rightSidebar.review.actions.stageHunk') : t('rightSidebar.review.actions.unstageHunk');
+ return action === 'stage'
+ ? t('rightSidebar.review.actions.stageHunk')
+ : t('rightSidebar.review.actions.unstageHunk');
}
function allActionLabel(action: ReviewToggleAction, t: (key: string) => string): string {
- return action === 'stage' ? t('rightSidebar.review.actions.stageAll') : t('rightSidebar.review.actions.unstageAll');
+ return action === 'stage'
+ ? t('rightSidebar.review.actions.stageAll')
+ : t('rightSidebar.review.actions.unstageAll');
}
-export function actionForReviewDiff(source: ReviewSource, diff: Pick<FileDiff, 'source'>): ReviewToggleAction | null {
+export function actionForReviewDiff(
+ source: ReviewSource,
+ diff: Pick<FileDiff, 'source'>,
+): ReviewToggleAction | null {
void diff;
if (source === 'unstaged') return 'stage';
if (source === 'staged') return 'unstage';
return null;
}
-export function discardForReviewDiff(source: ReviewSource, diff: Pick<FileDiff, 'source'>): boolean {
+export function discardForReviewDiff(
+ source: ReviewSource,
+ diff: Pick<FileDiff, 'source'>,
+): boolean {
if (source === 'unstaged') return diff.source === 'unstaged';
return false;
}
@@ -2560,10 +2827,11 @@ function OperationNotice({
if (!error && failed.length === 0) return null;
return (
<div className="mt-2 rounded-[8px] border border-[var(--error-border)] bg-[var(--error-bg)] px-2.5 py-2 text-11 leading-relaxed text-[var(--error-fg)]">
- {errorTitle ?? t('rightSidebar.review.actions.partialFailure', {
- succeeded: summary?.succeeded.length ?? 0,
- failed: failed.length,
- })}
+ {errorTitle ??
+ t('rightSidebar.review.actions.partialFailure', {
+ succeeded: summary?.succeeded.length ?? 0,
+ failed: failed.length,
+ })}
{errorDetails && (
<div className="mt-1 max-h-24 overflow-auto whitespace-pre-wrap break-words font-mono text-10 text-[var(--error-fg-strong)]">
{errorDetails}
@@ -2615,6 +2883,7 @@ function DiffList({
loadImagePreview,
loadMarkdownPreview,
richMarkdownPreview,
+ richMarkdownPreviewDisabledReason,
onOpenFile,
writeAction,
}: {
@@ -2635,6 +2904,7 @@ function DiffList({
loadImagePreview: LoadImagePreview;
loadMarkdownPreview: LoadMarkdownPreview;
richMarkdownPreview: boolean;
+ richMarkdownPreviewDisabledReason?: string;
onOpenFile?: (diff: FileDiff) => void;
writeAction?: WriteActionProps;
}) {
@@ -2659,7 +2929,7 @@ function DiffList({
const fileVirtualizer = useVirtualizer({
count: diffs.length,
getScrollElement: () => parentRef.current,
- estimateSize: (index) => expandedSet.has(diffs[index]?.id) ? 360 : 45,
+ estimateSize: (index) => (expandedSet.has(diffs[index]?.id) ? 360 : 45),
overscan: 8,
getItemKey: (index) => diffs[index]?.id ?? index,
});
@@ -2699,16 +2969,22 @@ function DiffList({
}
}, []);
- const beginProgrammaticScrollSuppression = useCallback((targetId: string) => {
- endProgrammaticScrollSuppression();
- programmaticScrollSuppressedRef.current = true;
- programmaticScrollTargetRef.current = targetId;
- }, [endProgrammaticScrollSuppression]);
+ const beginProgrammaticScrollSuppression = useCallback(
+ (targetId: string) => {
+ endProgrammaticScrollSuppression();
+ programmaticScrollSuppressedRef.current = true;
+ programmaticScrollTargetRef.current = targetId;
+ },
+ [endProgrammaticScrollSuppression],
+ );
- useEffect(() => () => {
- if (scrollRafRef.current !== null) cancelAnimationFrame(scrollRafRef.current);
- endProgrammaticScrollSuppression();
- }, [endProgrammaticScrollSuppression]);
+ useEffect(
+ () => () => {
+ if (scrollRafRef.current !== null) cancelAnimationFrame(scrollRafRef.current);
+ endProgrammaticScrollSuppression();
+ },
+ [endProgrammaticScrollSuppression],
+ );
useEffect(() => {
const targetId = programmaticScrollTargetRef.current;
@@ -2732,12 +3008,15 @@ function DiffList({
if (pinnedTargetId && id === pinnedTargetId) {
endProgrammaticScrollSuppression();
}
- setActiveFileId((currentId) => nextReviewFileTreeActiveIdFromScroll({
- currentActiveFileId: currentId,
- candidateId: id,
- suppressed,
- pinnedTargetId,
- }).activeFileId);
+ setActiveFileId(
+ (currentId) =>
+ nextReviewFileTreeActiveIdFromScroll({
+ currentActiveFileId: currentId,
+ candidateId: id,
+ suppressed,
+ pinnedTargetId,
+ }).activeFileId,
+ );
}, [endProgrammaticScrollSuppression]);
const scheduleActiveFileSync = useCallback(() => {
@@ -2748,29 +3027,32 @@ function DiffList({
});
}, [syncActiveFileFromScroll]);
- const schedulePreciseScrollToFile = useCallback((targetId: string, attemptsLeft = 16) => {
- if (preciseScrollRafRef.current !== null) {
- cancelAnimationFrame(preciseScrollRafRef.current);
- }
- preciseScrollRafRef.current = requestAnimationFrame(() => {
- preciseScrollRafRef.current = null;
- const targetStillPinned = programmaticScrollTargetRef.current === targetId;
- const row = findFileRowElement(parentRef.current, targetId);
- const step = nextReviewFileJumpPreciseScrollStep({
- targetStillPinned,
- rowMounted: Boolean(row),
- attemptsLeft,
- });
- if (step.action === 'scroll' && row) {
- scrollElementIntoContainerView(parentRef.current, row, 'start');
- scheduleActiveFileSync();
- return;
+ const schedulePreciseScrollToFile = useCallback(
+ (targetId: string, attemptsLeft = 16) => {
+ if (preciseScrollRafRef.current !== null) {
+ cancelAnimationFrame(preciseScrollRafRef.current);
}
- if (step.action === 'retry') {
- schedulePreciseScrollToFile(targetId, step.nextAttemptsLeft);
- }
- });
- }, [scheduleActiveFileSync]);
+ preciseScrollRafRef.current = requestAnimationFrame(() => {
+ preciseScrollRafRef.current = null;
+ const targetStillPinned = programmaticScrollTargetRef.current === targetId;
+ const row = findFileRowElement(parentRef.current, targetId);
+ const step = nextReviewFileJumpPreciseScrollStep({
+ targetStillPinned,
+ rowMounted: Boolean(row),
+ attemptsLeft,
+ });
+ if (step.action === 'scroll' && row) {
+ scrollElementIntoContainerView(parentRef.current, row, 'start');
+ scheduleActiveFileSync();
+ return;
+ }
+ if (step.action === 'retry') {
+ schedulePreciseScrollToFile(targetId, step.nextAttemptsLeft);
+ }
+ });
+ },
+ [scheduleActiveFileSync],
+ );
const handleUserScrollIntent = useCallback(() => {
if (programmaticScrollTargetRef.current || programmaticScrollSuppressedRef.current) {
@@ -2778,23 +3060,37 @@ function DiffList({
}
}, [endProgrammaticScrollSuppression]);
- const handleUserScrollKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {
- if (isReviewFileTreeScrollKey(event.key)) {
- handleUserScrollIntent();
- }
- }, [handleUserScrollIntent]);
-
- const scrollToFile = useCallback((diff: FileDiff) => {
- setActiveFileId(diff.id);
- const index = diffs.findIndex((item) => item.id === diff.id);
- if (index < 0) return;
- beginProgrammaticScrollSuppression(diff.id);
- if (!expandedSet.has(diff.id)) onToggleDiff(diff.id);
- if (virtualized) {
- fileVirtualizer.scrollToIndex(index, { align: 'start' });
- }
- schedulePreciseScrollToFile(diff.id);
- }, [beginProgrammaticScrollSuppression, diffs, expandedSet, fileVirtualizer, onToggleDiff, schedulePreciseScrollToFile, virtualized]);
+ const handleUserScrollKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (isReviewFileTreeScrollKey(event.key)) {
+ handleUserScrollIntent();
+ }
+ },
+ [handleUserScrollIntent],
+ );
+
+ const scrollToFile = useCallback(
+ (diff: FileDiff) => {
+ setActiveFileId(diff.id);
+ const index = diffs.findIndex((item) => item.id === diff.id);
+ if (index < 0) return;
+ beginProgrammaticScrollSuppression(diff.id);
+ if (!expandedSet.has(diff.id)) onToggleDiff(diff.id);
+ if (virtualized) {
+ fileVirtualizer.scrollToIndex(index, { align: 'start' });
+ }
+ schedulePreciseScrollToFile(diff.id);
+ },
+ [
+ beginProgrammaticScrollSuppression,
+ diffs,
+ expandedSet,
+ fileVirtualizer,
+ onToggleDiff,
+ schedulePreciseScrollToFile,
+ virtualized,
+ ],
+ );
useEffect(() => {
if (!jumpRequest || consumedJumpNonceRef.current === jumpRequest.nonce) return;
@@ -2837,6 +3133,7 @@ function DiffList({
viewMode={viewMode}
onViewModeChange={onViewModeChange}
richMarkdownPreview={richMarkdownPreview}
+ richMarkdownPreviewDisabledReason={richMarkdownPreviewDisabledReason}
onRichMarkdownPreviewChange={onRichMarkdownPreviewChange}
/>
{topNotice && (
@@ -2859,10 +3156,7 @@ function DiffList({
onKeyDownCapture={handleUserScrollKeyDown}
className={cn('h-full min-h-0 min-w-0 overflow-y-auto', hasBatchActions && 'pb-14')}
>
- <div
- className="relative w-full"
- style={{ height: fileVirtualizer.getTotalSize() }}
- >
+ <div className="relative w-full" style={{ height: fileVirtualizer.getTotalSize() }}>
{fileVirtualizer.getVirtualItems().map((item) => {
const diff = diffs[item.index];
if (!diff) return null;
@@ -2889,7 +3183,10 @@ function DiffList({
onTouchStart={handleUserScrollIntent}
onPointerDownCapture={handleUserScrollIntent}
onKeyDownCapture={handleUserScrollKeyDown}
- className={cn('flex h-full min-h-0 min-w-0 flex-col overflow-y-auto', hasBatchActions && 'pb-14')}
+ className={cn(
+ 'flex h-full min-h-0 min-w-0 flex-col overflow-y-auto',
+ hasBatchActions && 'pb-14',
+ )}
>
{diffs.map(renderFileRow)}
</div>
@@ -2924,7 +3221,9 @@ function findFileRowElement(container: HTMLElement | null, id: string): HTMLElem
function findFileTreeRowElement(container: HTMLElement | null, id: string): HTMLElement | null {
if (!container) return null;
- const rows = Array.from(container.querySelectorAll<HTMLElement>('[data-review-file-tree-node-id]'));
+ const rows = Array.from(
+ container.querySelectorAll<HTMLElement>('[data-review-file-tree-node-id]'),
+ );
return rows.find((row) => row.dataset.reviewFileTreeNodeId === id) ?? null;
}
@@ -3021,7 +3320,10 @@ export function ReviewFileTreeSidebar({
>
<div className="shrink-0 border-b border-[var(--border-default)] p-2">
<label className="relative block">
- <Search size={12} className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]" />
+ <Search
+ size={12}
+ className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]"
+ />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
@@ -3096,7 +3398,11 @@ function ReviewFileTreeRow({
className="flex h-7 w-full min-w-0 items-center gap-1 pr-2 text-left text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]"
style={{ paddingLeft }}
>
- {collapsed ? <ChevronRight size={12} className="shrink-0 text-[var(--text-tertiary)]" /> : <ChevronDown size={12} className="shrink-0 text-[var(--text-tertiary)]" />}
+ {collapsed ? (
+ <ChevronRight size={12} className="shrink-0 text-[var(--text-tertiary)]" />
+ ) : (
+ <ChevronDown size={12} className="shrink-0 text-[var(--text-tertiary)]" />
+ )}
<span className="min-w-0 truncate font-medium">{node.name}</span>
</button>
);
@@ -3178,6 +3484,7 @@ export function ReviewDiffListHeader({
viewMode,
onViewModeChange,
richMarkdownPreview,
+ richMarkdownPreviewDisabledReason,
onRichMarkdownPreviewChange,
}: {
fileCount: number;
@@ -3187,6 +3494,7 @@ export function ReviewDiffListHeader({
viewMode: DiffViewMode;
onViewModeChange: (mode: DiffViewMode) => void;
richMarkdownPreview: boolean;
+ richMarkdownPreviewDisabledReason?: string;
onRichMarkdownPreviewChange: (richMarkdownPreview: boolean) => void;
}) {
const { t } = useTranslation();
@@ -3211,12 +3519,21 @@ export function ReviewDiffListHeader({
}, [rowEl]);
return (
- <div ref={setRowEl} className="flex h-9 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-3 text-12">
- <div data-testid="review-diff-list-header-left" className="flex min-w-0 flex-1 items-center gap-2">
+ <div
+ ref={setRowEl}
+ className="flex h-9 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-3 text-12"
+ >
+ <div
+ data-testid="review-diff-list-header-left"
+ className="flex min-w-0 flex-1 items-center gap-2"
+ >
{branchBaseControl && (
<>
{showBranchBaseLabel && (
- <span data-testid="review-branch-base-label" className="shrink-0 text-11 text-[var(--text-tertiary)]">
+ <span
+ data-testid="review-branch-base-label"
+ className="shrink-0 text-11 text-[var(--text-tertiary)]"
+ >
{t('rightSidebar.review.branch.baseLabel')}
</span>
)}
@@ -3229,10 +3546,14 @@ export function ReviewDiffListHeader({
{t('rightSidebar.review.fileCount', { count: fileCount })}
</span>
</div>
- <div data-testid="review-diff-list-header-actions" className="ml-auto flex shrink-0 items-center gap-1">
+ <div
+ data-testid="review-diff-list-header-actions"
+ className="ml-auto flex shrink-0 items-center gap-1"
+ >
<ReviewRefreshButton pending={refreshPending} onRefresh={onRefresh} />
<RichMarkdownPreviewToggleButton
enabled={richMarkdownPreview}
+ disabledReason={richMarkdownPreviewDisabledReason}
onToggle={() => onRichMarkdownPreviewChange(!richMarkdownPreview)}
/>
<DiffViewModeToggle mode={viewMode} onChange={onViewModeChange} />
@@ -3243,25 +3564,34 @@ export function ReviewDiffListHeader({
function RichMarkdownPreviewToggleButton({
enabled,
+ disabledReason,
onToggle,
}: {
enabled: boolean;
+ disabledReason?: string;
onToggle: () => void;
}) {
const { t } = useTranslation();
- const label = t(enabled
- ? 'rightSidebar.review.moreMenu.richPreviewDisable'
- : 'rightSidebar.review.moreMenu.richPreviewEnable');
+ const label = t(
+ enabled
+ ? 'rightSidebar.review.moreMenu.richPreviewDisable'
+ : 'rightSidebar.review.moreMenu.richPreviewEnable',
+ );
return (
- <Tip text={label}>
+ <Tip text={disabledReason ?? label}>
<button
type="button"
+ aria-disabled={Boolean(disabledReason)}
aria-pressed={enabled}
aria-label={label}
- onClick={onToggle}
+ onClick={() => {
+ if (!disabledReason) onToggle();
+ }}
className={cn(
'flex h-6 w-6 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
enabled && 'bg-[var(--surface-chip)] text-[var(--text-primary)]',
+ disabledReason &&
+ 'cursor-not-allowed opacity-50 hover:bg-transparent hover:text-[var(--text-secondary)]',
)}
>
{enabled ? <Image size={13} /> : <ImageOff size={13} />}
@@ -3318,7 +3648,8 @@ function DiffViewModeToggle({
onClick={() => onChange(option.mode)}
className={cn(
'rounded-full px-2 text-10 font-medium text-[var(--text-secondary)] hover:text-[var(--text-primary)]',
- option.mode === mode && 'bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)]',
+ option.mode === mode &&
+ 'bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)]',
)}
>
{option.label}
@@ -3440,7 +3771,11 @@ export function CappedSourceView({
<div className="flex h-full min-h-0 min-w-0">
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
{!selectedSummaryDiff ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.emptyTitle')} desc={t('rightSidebar.review.emptyDescGit')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.emptyTitle')}
+ desc={t('rightSidebar.review.emptyDescGit')}
+ />
) : loading ? (
<CappedFileState
icon={<Spinner icon={RefreshCw} size={20} />}
@@ -3491,15 +3826,7 @@ export function CappedSourceView({
);
}
-function CappedFileState({
- icon,
- title,
- desc,
-}: {
- icon: ReactNode;
- title: string;
- desc: string;
-}) {
+function CappedFileState({ icon, title, desc }: { icon: ReactNode; title: string; desc: string }) {
return (
<div className="m-3 rounded-[8px] border border-[var(--border-default)] bg-[var(--surface)] px-3 py-3 text-12 leading-relaxed text-[var(--text-secondary)]">
<div className="flex items-center gap-2 font-medium text-[var(--text-primary)]">
@@ -3559,19 +3886,43 @@ function CommitSourceView({
const { t } = useTranslation();
if (!selectedCommitOid) {
- return <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.noCommitsTitle')} desc={t('rightSidebar.review.noCommitsDesc')} />;
+ return (
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.noCommitsTitle')}
+ desc={t('rightSidebar.review.noCommitsDesc')}
+ />
+ );
}
return (
<div className="flex min-h-0 flex-1 flex-col">
{diffLoading ? (
- <CenteredState icon={<Spinner icon={RefreshCw} size={24} />} title={t('rightSidebar.review.commitDiffLoadingTitle')} desc={selectedCommitOid.slice(0, 7)} />
+ <CenteredState
+ icon={<Spinner icon={RefreshCw} size={24} />}
+ title={t('rightSidebar.review.commitDiffLoadingTitle')}
+ desc={selectedCommitOid.slice(0, 7)}
+ />
) : diffError && diffs.length === 0 ? (
- <CenteredState icon={<AlertTriangle size={24} />} title={t('rightSidebar.review.commitDiffErrorTitle')} desc={diffError} actionLabel={t('rightSidebar.review.refresh')} onAction={onRefreshDiff} />
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.commitDiffErrorTitle')}
+ desc={diffError}
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={onRefreshDiff}
+ />
) : diffs.length === 0 && rawDiffCount > 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.filterEmptyTitle')} desc={t('rightSidebar.review.filterEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.filterEmptyTitle')}
+ desc={t('rightSidebar.review.filterEmptyDesc')}
+ />
) : diffs.length === 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.commitDiffEmptyTitle')} desc={t('rightSidebar.review.commitDiffEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.commitDiffEmptyTitle')}
+ desc={t('rightSidebar.review.commitDiffEmptyDesc')}
+ />
) : (
<DiffList
diffs={diffs}
@@ -3651,22 +4002,54 @@ function BranchSourceView({
const blockingWarning = warning && warning.code !== 'base-missing' ? warning : null;
if (diffLoading) {
- return <CenteredState icon={<Spinner icon={RefreshCw} size={24} />} title={t('rightSidebar.review.branch.loadingTitle')} desc={t('rightSidebar.review.branch.loadingDesc')} />;
+ return (
+ <CenteredState
+ icon={<Spinner icon={RefreshCw} size={24} />}
+ title={t('rightSidebar.review.branch.loadingTitle')}
+ desc={t('rightSidebar.review.branch.loadingDesc')}
+ />
+ );
}
if (diffError && rawDiffCount === 0) {
- return <CenteredState icon={<AlertTriangle size={24} />} title={t('rightSidebar.review.branch.errorTitle')} desc={diffError} actionLabel={t('rightSidebar.review.refresh')} onAction={onRefreshDiff} />;
+ return (
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.branch.errorTitle')}
+ desc={diffError}
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={onRefreshDiff}
+ />
+ );
}
return (
<div className="flex min-h-0 flex-1 flex-col">
{candidates.length === 0 ? (
- <CenteredState icon={<GitBranch size={24} />} title={t('rightSidebar.review.branch.noCandidatesTitle')} desc={t('rightSidebar.review.branch.noCandidatesDesc')} />
+ <CenteredState
+ icon={<GitBranch size={24} />}
+ title={t('rightSidebar.review.branch.noCandidatesTitle')}
+ desc={t('rightSidebar.review.branch.noCandidatesDesc')}
+ />
) : blockingWarning ? (
- <CenteredState icon={<AlertTriangle size={24} />} title={t('rightSidebar.review.branch.warningTitle')} desc={branchWarningText(blockingWarning, t)} actionLabel={t('rightSidebar.review.refresh')} onAction={onRefreshDiff} />
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.branch.warningTitle')}
+ desc={branchWarningText(blockingWarning, t)}
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={onRefreshDiff}
+ />
) : diffs.length === 0 && rawDiffCount > 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.filterEmptyTitle')} desc={t('rightSidebar.review.filterEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.filterEmptyTitle')}
+ desc={t('rightSidebar.review.filterEmptyDesc')}
+ />
) : diffs.length === 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.branch.emptyTitle')} desc={t('rightSidebar.review.branch.emptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.branch.emptyTitle')}
+ desc={t('rightSidebar.review.branch.emptyDesc')}
+ />
) : (
<DiffList
diffs={diffs}
@@ -3674,13 +4057,13 @@ function BranchSourceView({
onToggleDiff={onToggleDiff}
onRefresh={onRefresh}
refreshPending={refreshPending}
- branchBaseControl={(
+ branchBaseControl={
<BranchBaseDropdown
candidates={candidates}
selectedBaseRef={selectedBaseRef}
onSelectBase={onSelectBase}
/>
- )}
+ }
topNotice={warning && !blockingWarning ? branchWarningText(warning, t) : null}
viewMode={viewMode}
onViewModeChange={onViewModeChange}
@@ -3709,7 +4092,8 @@ export function BranchBaseDropdown({
onSelectBase: (baseRef: string) => void;
}) {
const { t } = useTranslation();
- const selected = candidates.find((candidate) => candidate.refName === selectedBaseRef) ?? candidates[0] ?? null;
+ const selected =
+ candidates.find((candidate) => candidate.refName === selectedBaseRef) ?? candidates[0] ?? null;
const label = selected?.shortName ?? t('rightSidebar.review.branch.basePlaceholder');
const tooltip = selected
? t('rightSidebar.review.branch.baseTooltip', { base: selected.refName })
@@ -3759,14 +4143,20 @@ export function BranchBaseDropdown({
);
}
-function branchWarningText(warning: ReviewBranchDiffWarning, t: (key: string, opts?: Record<string, unknown>) => string): string {
+function branchWarningText(
+ warning: ReviewBranchDiffWarning,
+ t: (key: string, opts?: Record<string, unknown>) => string,
+): string {
switch (warning.code) {
case 'base-missing':
return t('rightSidebar.review.branch.baseMissing', { base: warning.requestedBaseRef ?? '' });
case 'merge-base-missing':
return t('rightSidebar.review.branch.mergeBaseMissing');
case 'too-many-files':
- return t('rightSidebar.review.branch.tooManyFiles', { count: warning.fileCount ?? 0, limit: warning.limit ?? 0 });
+ return t('rightSidebar.review.branch.tooManyFiles', {
+ count: warning.fileCount ?? 0,
+ limit: warning.limit ?? 0,
+ });
case 'unborn':
return t('rightSidebar.review.branch.unborn');
case 'no-base-candidates':
@@ -3848,7 +4238,13 @@ function ActionButton({
if (!iconOnly && (!disabled || !disabledTooltip)) return button;
return (
<Tip text={disabled && disabledTooltip ? disabledTooltip : label}>
- <span className={cn('inline-flex', className?.includes('w-full') && 'w-full', className?.includes('flex-1') && 'flex-1')}>
+ <span
+ className={cn(
+ 'inline-flex',
+ className?.includes('w-full') && 'w-full',
+ className?.includes('flex-1') && 'flex-1',
+ )}
+ >
{button}
</span>
</Tip>
@@ -3911,9 +4307,17 @@ function StagedSourceView({
return (
<div className="flex min-h-0 flex-1 flex-col">
{filteredEmpty ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.filterEmptyTitle')} desc={t('rightSidebar.review.filterEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.filterEmptyTitle')}
+ desc={t('rightSidebar.review.filterEmptyDesc')}
+ />
) : diffs.length === 0 ? (
- <CenteredState icon={<FileDiffIcon size={24} />} title={t('rightSidebar.review.stagedEmptyTitle')} desc={t('rightSidebar.review.stagedEmptyDesc')} />
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.stagedEmptyTitle')}
+ desc={t('rightSidebar.review.stagedEmptyDesc')}
+ />
) : (
<DiffList
diffs={diffs}
@@ -3983,36 +4387,53 @@ function FileRow({
const canDiscard = writeAction?.discardForDiff?.(diff) ?? false;
const filePending = action ? writeAction?.pendingKey === `${action}:file:${diff.id}` : false;
const discardFilePending = writeAction?.pendingKey === `discard:file:${diff.id}`;
- const hasFileActions = Boolean(writeAction && ((canDiscard && writeAction.onFileDiscard) || action));
+ const hasFileActions = Boolean(
+ writeAction && ((canDiscard && writeAction.onFileDiscard) || action),
+ );
const fileActionsPending = Boolean(filePending || discardFilePending);
const hunkActionsEnabled = writeAction?.hunkActionsEnabled ?? true;
const canPartial = hunkActionsEnabled && partialAllowed(diff);
const showRenamePartialNotice = Boolean(hunkActionsEnabled && action && isRenameLikeDiff(diff));
- const showTypechangePartialNotice = Boolean(hunkActionsEnabled && action && isTypechangeLikeDiff(diff));
- const showsPathTransition = Boolean(diff.oldPath && (diff.status === 'renamed' || diff.status === 'copied'));
+ const showTypechangePartialNotice = Boolean(
+ hunkActionsEnabled && action && isTypechangeLikeDiff(diff),
+ );
+ const showsPathTransition = Boolean(
+ diff.oldPath && (diff.status === 'renamed' || diff.status === 'copied'),
+ );
const richMarkdownEligibility = getRichMarkdownPreviewEligibility(diff, richMarkdownPreview);
- const changeChip = diff.status === 'renamed'
- ? t('rightSidebar.review.changeStatus.renamed')
- : diff.status === 'copied'
- ? t('rightSidebar.review.changeStatus.copied')
- : null;
+ const changeChip =
+ diff.status === 'renamed'
+ ? t('rightSidebar.review.changeStatus.renamed')
+ : diff.status === 'copied'
+ ? t('rightSidebar.review.changeStatus.copied')
+ : null;
const hunkActions = [
- ...(writeAction && canDiscard && canPartial && writeAction.onHunkDiscard ? [{
- label: t('rightSidebar.review.actions.discardHunk'),
- disabled: !writeAction.canWrite,
- disabledTooltip: !writeAction.canWrite ? writeAction.disabledTooltip : undefined,
- isPending: (hunkIndex: number) => writeAction.pendingKey === `discard:hunk:${diff.id}:${hunkIndex}`,
- onClick: (hunkIndex: number) => writeAction.onHunkDiscard?.(diff, hunkIndex),
- icon: 'revert' as const,
- }] : []),
- ...(writeAction && action && canPartial ? [{
- label: hunkActionLabel(action, t),
- disabled: !writeAction.canWrite,
- disabledTooltip: !writeAction.canWrite ? writeAction.disabledTooltip : undefined,
- isPending: (hunkIndex: number) => writeAction.pendingKey === `${action}:hunk:${diff.id}:${hunkIndex}`,
- onClick: (hunkIndex: number) => writeAction.onHunkAction(diff, hunkIndex),
- icon: action === 'stage' ? 'plus' as const : 'minus' as const,
- }] : []),
+ ...(writeAction && canDiscard && canPartial && writeAction.onHunkDiscard
+ ? [
+ {
+ label: t('rightSidebar.review.actions.discardHunk'),
+ disabled: !writeAction.canWrite,
+ disabledTooltip: !writeAction.canWrite ? writeAction.disabledTooltip : undefined,
+ isPending: (hunkIndex: number) =>
+ writeAction.pendingKey === `discard:hunk:${diff.id}:${hunkIndex}`,
+ onClick: (hunkIndex: number) => writeAction.onHunkDiscard?.(diff, hunkIndex),
+ icon: 'revert' as const,
+ },
+ ]
+ : []),
+ ...(writeAction && action && canPartial
+ ? [
+ {
+ label: hunkActionLabel(action, t),
+ disabled: !writeAction.canWrite,
+ disabledTooltip: !writeAction.canWrite ? writeAction.disabledTooltip : undefined,
+ isPending: (hunkIndex: number) =>
+ writeAction.pendingKey === `${action}:hunk:${diff.id}:${hunkIndex}`,
+ onClick: (hunkIndex: number) => writeAction.onHunkAction(diff, hunkIndex),
+ icon: action === 'stage' ? ('plus' as const) : ('minus' as const),
+ },
+ ]
+ : []),
];
const plainDiffBody = (
<PlainUnifiedDiff
@@ -4033,10 +4454,12 @@ function FileRow({
data-review-file-id={diff.id}
className="group/file min-w-0 border-b border-[var(--border-default)]"
>
- <div className={cn(
- 'relative flex w-full items-center gap-2 px-3 py-2 hover:bg-[var(--surface-hover)]',
- hasFileActions && 'pr-20',
- )}>
+ <div
+ className={cn(
+ 'relative flex w-full items-center gap-2 px-3 py-2 hover:bg-[var(--surface-hover)]',
+ hasFileActions && 'pr-20',
+ )}
+ >
<button
type="button"
onClick={onToggle}
@@ -4049,7 +4472,9 @@ function FileRow({
<ChevronRight size={12} className="shrink-0 text-[var(--text-tertiary)]" />
)}
<span className="min-w-0 flex-1">
- <span className="block truncate text-13 font-medium text-[var(--text-primary)]">{fileName}</span>
+ <span className="block truncate text-13 font-medium text-[var(--text-primary)]">
+ {fileName}
+ </span>
<span className="block truncate text-10 text-[var(--text-tertiary)]">
{showsPathTransition ? (
<>
@@ -4057,7 +4482,9 @@ function FileRow({
<span className="px-1">→</span>
<span>{diff.path}</span>
</>
- ) : diff.path}
+ ) : (
+ diff.path
+ )}
</span>
</span>
</button>
@@ -4127,7 +4554,9 @@ function FileRow({
fallback={plainDiffBody}
onPreviewSettled={onImagePreviewLoad}
/>
- ) : plainDiffBody}
+ ) : (
+ plainDiffBody
+ )}
</div>
)}
</div>
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 8b0c434fdf..84eb088c39 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
@@ -42,6 +42,7 @@ import {
refreshBranchDiffAfterCommit,
revealReviewFileTreeActiveNode,
reviewActionRevealClass,
+ reviewSourceStatePatch,
scrollElementIntoContainerView,
shouldShowBranchBaseLabel,
shouldOfferReviewOpenFile,
@@ -53,7 +54,11 @@ import {
useClearReviewOperationNoticeOnSourceChange,
} from '../ReviewTabBody';
-function diff(source: FileDiff['source'], path: string, overrides: Partial<FileDiff> = {}): FileDiff {
+function diff(
+ source: FileDiff['source'],
+ path: string,
+ overrides: Partial<FileDiff> = {},
+): FileDiff {
return {
id: `${source}:${path}`,
source,
@@ -124,12 +129,15 @@ describe('ReviewTabBody Last turn actions', () => {
expect(discardForReviewDiff('last-turn', diff('unstaged', 'a.ts'))).toBe(false);
expect(discardForReviewDiff('last-turn', diff('staged', 'b.ts'))).toBe(false);
expect(discardForReviewDiff('commit' as ReviewSource, diff('unstaged', 'a.ts'))).toBe(false);
- expect(discardForReviewDiff('branch' as ReviewSource, diff('branch', 'feature.ts'))).toBe(false);
-
- expect(lastTurnDiscardableDiffs([
- diff('staged', 'already.ts'),
- diff('unstaged', 'worktree.ts'),
- ]).map((item) => item.path)).toEqual([]);
+ expect(discardForReviewDiff('branch' as ReviewSource, diff('branch', 'feature.ts'))).toBe(
+ false,
+ );
+
+ expect(
+ lastTurnDiscardableDiffs([diff('staged', 'already.ts'), diff('unstaged', 'worktree.ts')]).map(
+ (item) => item.path,
+ ),
+ ).toEqual([]);
});
});
@@ -139,29 +147,38 @@ describe('ReviewTabBody hunk action eligibility', () => {
});
it('disables patch-based hunk actions for deleted files', () => {
- expect(partialAllowed(diff('unstaged', 'deleted.txt', {
- status: 'deleted',
- }))).toBe(false);
+ expect(
+ partialAllowed(
+ diff('unstaged', 'deleted.txt', {
+ status: 'deleted',
+ }),
+ ),
+ ).toBe(false);
});
it('disables patch-based hunk actions for typechange and mode changes', () => {
expect(partialAllowed(diff('unstaged', 'file.txt'))).toBe(true);
- expect(partialAllowed(diff('unstaged', 'link.txt', {
- status: 'typechange',
- mode: { old: '100644', new: '120000' },
- }))).toBe(false);
- expect(partialAllowed(diff('unstaged', 'script.sh', {
- mode: { old: '100644', new: '100755' },
- }))).toBe(false);
+ expect(
+ partialAllowed(
+ diff('unstaged', 'link.txt', {
+ status: 'typechange',
+ mode: { old: '100644', new: '120000' },
+ }),
+ ),
+ ).toBe(false);
+ expect(
+ partialAllowed(
+ diff('unstaged', 'script.sh', {
+ mode: { old: '100644', new: '100755' },
+ }),
+ ),
+ ).toBe(false);
});
});
describe('ReviewTabBody diff expansion state', () => {
it('expands every visible diff by default and removes collapsed ids only', () => {
- const diffs = [
- diff('unstaged', 'a.ts'),
- diff('unstaged', 'b.ts'),
- ];
+ const diffs = [diff('unstaged', 'a.ts'), diff('unstaged', 'b.ts')];
expect(Array.from(getExpandedDiffSet(diffs, new Set()))).toEqual([
'unstaged:a.ts',
@@ -173,13 +190,25 @@ describe('ReviewTabBody diff expansion state', () => {
});
});
+describe('ReviewTabBody source state', () => {
+ it('replaces the descriptor and clears entry-only positioning state', () => {
+ expect(reviewSourceStatePatch({ kind: 'branch', baseRef: 'main' })).toEqual({
+ descriptor: { kind: 'branch', baseRef: 'main' },
+ jumpTarget: null,
+ turnTarget: null,
+ });
+ });
+});
+
describe('ReviewTabBody compact source dropdown', () => {
it('uses a compact toolbar trigger instead of a full-width control', () => {
- render(createElement(SourceDropdown, {
- source: 'unstaged',
- counts: { unstaged: 2, staged: 1, branch: 0, lastTurn: 1 },
- onChange: vi.fn(),
- }));
+ render(
+ createElement(SourceDropdown, {
+ source: 'unstaged',
+ counts: { unstaged: 2, staged: 1, branch: 0, lastTurn: 1 },
+ onChange: vi.fn(),
+ }),
+ );
const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.className).toContain('max-w-[11rem]');
@@ -187,67 +216,79 @@ describe('ReviewTabBody compact source dropdown', () => {
});
it('uses a source trigger wide enough for localized labels in compact toolbar layouts', () => {
- const { rerender } = render(createElement(SourceDropdown, {
- source: 'unstaged',
- counts: { unstaged: 2, staged: 1, branch: 0, lastTurn: 1 },
- layout: 'minimal',
- onChange: vi.fn(),
- }));
+ const { rerender } = render(
+ createElement(SourceDropdown, {
+ source: 'unstaged',
+ counts: { unstaged: 2, staged: 1, branch: 0, lastTurn: 1 },
+ layout: 'minimal',
+ onChange: vi.fn(),
+ }),
+ );
let trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.className).toContain('max-w-[10rem]');
- rerender(createElement(SourceDropdown, {
- source: 'staged',
- counts: { unstaged: 2, staged: 12, branch: 0, lastTurn: 1 },
- layout: 'compact',
- onChange: vi.fn(),
- }));
+ rerender(
+ createElement(SourceDropdown, {
+ source: 'staged',
+ counts: { unstaged: 2, staged: 12, branch: 0, lastTurn: 1 },
+ layout: 'compact',
+ onChange: vi.fn(),
+ }),
+ );
trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.className).toContain('max-w-[10rem]');
});
it('renders source counts as positive badges only for dirty worktree sources', () => {
- const { rerender } = render(createElement(SourceDropdown, {
- source: 'unstaged',
- counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
- onChange: vi.fn(),
- }));
+ const { rerender } = render(
+ createElement(SourceDropdown, {
+ source: 'unstaged',
+ counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
+ onChange: vi.fn(),
+ }),
+ );
let trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(within(trigger).getByText('2')).toBeTruthy();
expect(trigger.textContent).not.toContain('4');
expect(trigger.textContent).not.toContain('3');
- rerender(createElement(SourceDropdown, {
- source: 'branch',
- counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
- onChange: vi.fn(),
- }));
+ rerender(
+ createElement(SourceDropdown, {
+ source: 'branch',
+ counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
+ onChange: vi.fn(),
+ }),
+ );
trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.textContent).toBe('rightSidebar.review.source.branch');
- rerender(createElement(SourceDropdown, {
- source: 'staged',
- counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
- onChange: vi.fn(),
- }));
+ rerender(
+ createElement(SourceDropdown, {
+ source: 'staged',
+ counts: { unstaged: 2, staged: 0, branch: 4, lastTurn: 3 },
+ onChange: vi.fn(),
+ }),
+ );
trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.textContent).toBe('rightSidebar.review.source.staged');
});
});
describe('ReviewTabBody turn source dropdown', () => {
- // 轮次审查(turnTarget)与 Git 审查共用同一个来源下拉:轮次态下选中项是
+ // 轮次 descriptor 与 Git 审查共用同一个来源下拉:轮次态下选中项是
// 轮次伪选项,git 来源仍全部可选——这是"从轮次视图切回 git 审查不需要
// 关掉重开 tab"的回归钉。
it('shows the turn pseudo-source as the selected trigger label', () => {
- render(createElement(SourceDropdown, {
- source: 'turn',
- counts: {},
- onChange: vi.fn(),
- }));
+ render(
+ createElement(SourceDropdown, {
+ source: 'turn',
+ counts: {},
+ onChange: vi.fn(),
+ }),
+ );
const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
expect(trigger.textContent).toBe('rightSidebar.review.turn.title');
@@ -255,76 +296,110 @@ describe('ReviewTabBody turn source dropdown', () => {
it('lists git sources in turn mode and switches directly without close-reopen', async () => {
const onChange = vi.fn();
- render(createElement(SourceDropdown, {
- source: 'turn',
- counts: {},
- onChange,
- }));
+ render(
+ createElement(SourceDropdown, {
+ source: 'turn',
+ counts: {},
+ onChange,
+ }),
+ );
const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
fireEvent.keyDown(trigger, { key: 'Enter' });
- expect(await screen.findByRole('menuitem', { name: 'rightSidebar.review.turn.title' })).toBeTruthy();
+ expect(
+ await screen.findByRole('menuitem', { name: 'rightSidebar.review.turn.title' }),
+ ).toBeTruthy();
fireEvent.click(screen.getByRole('menuitem', { name: 'rightSidebar.review.source.unstaged' }));
expect(onChange).toHaveBeenCalledWith('unstaged');
});
it('keeps the turn pseudo-item selection-only (no source change on click)', async () => {
const onChange = vi.fn();
- render(createElement(SourceDropdown, {
- source: 'turn',
- counts: {},
- onChange,
- }));
+ render(
+ createElement(SourceDropdown, {
+ source: 'turn',
+ counts: {},
+ onChange,
+ }),
+ );
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' }));
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'rightSidebar.review.turn.title' }),
+ );
expect(onChange).not.toHaveBeenCalled();
});
it('does not offer the turn pseudo-item while a git source is active', async () => {
- render(createElement(SourceDropdown, {
- source: 'unstaged',
- counts: { unstaged: 0, staged: 0, branch: 0, lastTurn: 0 },
- onChange: vi.fn(),
- }));
+ render(
+ createElement(SourceDropdown, {
+ source: 'unstaged',
+ counts: { unstaged: 0, staged: 0, branch: 0, lastTurn: 0 },
+ onChange: vi.fn(),
+ }),
+ );
const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
fireEvent.keyDown(trigger, { key: 'Enter' });
await screen.findByRole('menuitem', { name: 'rightSidebar.review.source.unstaged' });
expect(screen.queryByRole('menuitem', { name: 'rightSidebar.review.turn.title' })).toBeNull();
});
+
+ it('keeps the same source trigger visible but inert for cross-session snapshots', () => {
+ const onChange = vi.fn();
+ render(
+ createElement(SourceDropdown, {
+ source: 'turn',
+ counts: {},
+ disabledReason: 'cross-session',
+ onChange,
+ }),
+ );
+
+ const trigger = screen.getByRole('button', { name: 'rightSidebar.review.sourceDropdownAria' });
+ expect(trigger.getAttribute('aria-disabled')).toBe('true');
+ expect(trigger.className).toContain('cursor-not-allowed');
+ fireEvent.keyDown(trigger, { key: 'Enter' });
+ expect(screen.queryByRole('menuitem')).toBeNull();
+ expect(onChange).not.toHaveBeenCalled();
+ });
});
describe('ReviewTabBody branch base dropdown', () => {
it('marks stale local branch candidates with a tertiary text suffix', () => {
- render(createElement(BranchBaseDropdown, {
- candidates: [
- {
- refName: 'origin/main',
- shortName: 'origin/main',
- kind: 'remote-default',
- remote: 'origin',
- oid: 'a'.repeat(40),
- },
- {
- refName: 'main',
- shortName: 'main',
- kind: 'local',
- remote: null,
- oid: 'b'.repeat(40),
- isStaleRisk: true,
- },
- ],
- selectedBaseRef: 'origin/main',
- onSelectBase: vi.fn(),
- }));
-
- fireEvent.pointerDown(screen.getByRole('button', { name: 'rightSidebar.review.branch.baseTooltip' }), {
- button: 0,
- ctrlKey: false,
- });
+ render(
+ createElement(BranchBaseDropdown, {
+ candidates: [
+ {
+ refName: 'origin/main',
+ shortName: 'origin/main',
+ kind: 'remote-default',
+ remote: 'origin',
+ oid: 'a'.repeat(40),
+ },
+ {
+ refName: 'main',
+ shortName: 'main',
+ kind: 'local',
+ remote: null,
+ oid: 'b'.repeat(40),
+ isStaleRisk: true,
+ },
+ ],
+ selectedBaseRef: 'origin/main',
+ onSelectBase: vi.fn(),
+ }),
+ );
+
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'rightSidebar.review.branch.baseTooltip' }),
+ {
+ button: 0,
+ ctrlKey: false,
+ },
+ );
const suffix = screen.getByText('rightSidebar.review.branch.staleRiskSuffix');
expect(suffix.className).toContain('text-[var(--text-tertiary)]');
@@ -335,10 +410,12 @@ describe('ReviewTabBody branch base dropdown', () => {
describe('ReviewTabBody refresh control', () => {
it('uses a descriptive aria label and shows pending state', () => {
const onRefresh = vi.fn();
- render(createElement(ReviewRefreshButton, {
- pending: true,
- onRefresh,
- }));
+ render(
+ createElement(ReviewRefreshButton, {
+ pending: true,
+ onRefresh,
+ }),
+ );
const button = screen.getByRole('button', { name: 'rightSidebar.review.refreshGitData' });
expect(button.querySelector('.animate-spin')).toBeTruthy();
@@ -361,29 +438,34 @@ describe('ReviewTabBody more menu state icons', () => {
diffExpansionAction: 'expand' | 'collapse';
fileTreeVisible: boolean;
}) {
- render(createElement(ReviewMoreMenu, {
- wordWrap,
- wordDiff,
- hideWhitespace,
- diffExpansionOverflow: {
- action: diffExpansionAction,
- onToggle: vi.fn(),
- },
- fileTreeOverflow: {
- preferenceVisible: fileTreeVisible,
- temporarilyHidden: false,
- onToggle: vi.fn(),
+ render(
+ createElement(ReviewMoreMenu, {
+ wordWrap,
+ wordDiff,
+ hideWhitespace,
+ diffExpansionOverflow: {
+ action: diffExpansionAction,
+ onToggle: vi.fn(),
+ },
+ fileTreeOverflow: {
+ preferenceVisible: fileTreeVisible,
+ temporarilyHidden: false,
+ onToggle: vi.fn(),
+ },
+ canCopyGitApply: true,
+ onWordWrapChange: vi.fn(),
+ onWordDiffChange: vi.fn(),
+ onHideWhitespaceChange: vi.fn(),
+ onCopyGitApply: vi.fn(),
+ }),
+ );
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'rightSidebar.review.moreMenu.aria' }),
+ {
+ button: 0,
+ ctrlKey: false,
},
- canCopyGitApply: true,
- onWordWrapChange: vi.fn(),
- onWordDiffChange: vi.fn(),
- onHideWhitespaceChange: vi.fn(),
- onCopyGitApply: vi.fn(),
- }));
- fireEvent.pointerDown(screen.getByRole('button', { name: 'rightSidebar.review.moreMenu.aria' }), {
- button: 0,
- ctrlKey: false,
- });
+ );
}
it('shows current-state icons next to action text when toggles are enabled', () => {
@@ -423,19 +505,25 @@ describe('ReviewTabBody more menu state icons', () => {
describe('ReviewTabBody diff list header', () => {
it('keeps branch base selector shrinkable without squeezing refresh and view mode controls', () => {
- render(createElement(ReviewDiffListHeader, {
- fileCount: 5,
- branchBaseControl: createElement('button', {
- type: 'button',
- className: 'truncate',
- }, 'feature/a-very-long-branch-name-that-must-not-push-actions-away'),
- refreshPending: false,
- onRefresh: vi.fn(),
- viewMode: 'split',
- onViewModeChange: vi.fn(),
- richMarkdownPreview: true,
- onRichMarkdownPreviewChange: vi.fn(),
- }));
+ render(
+ createElement(ReviewDiffListHeader, {
+ fileCount: 5,
+ branchBaseControl: createElement(
+ 'button',
+ {
+ type: 'button',
+ className: 'truncate',
+ },
+ 'feature/a-very-long-branch-name-that-must-not-push-actions-away',
+ ),
+ refreshPending: false,
+ onRefresh: vi.fn(),
+ viewMode: 'split',
+ onViewModeChange: vi.fn(),
+ richMarkdownPreview: true,
+ onRichMarkdownPreviewChange: vi.fn(),
+ }),
+ );
expect(screen.getByTestId('review-diff-list-header-left').className).toContain('min-w-0');
expect(screen.getByTestId('review-diff-list-header-left').className).toContain('flex-1');
@@ -443,24 +531,30 @@ describe('ReviewTabBody diff list header', () => {
expect(screen.getByTestId('review-branch-base-control').className).toContain('max-w-[8.5rem]');
expect(screen.getByTestId('review-diff-list-header-actions').className).toContain('shrink-0');
expect(screen.getByRole('button', { name: 'rightSidebar.review.refreshGitData' })).toBeTruthy();
- expect(screen.getByRole('button', { name: 'rightSidebar.review.moreMenu.richPreviewDisable' })).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.review.moreMenu.richPreviewDisable' }),
+ ).toBeTruthy();
expect(screen.queryByTestId('review-branch-base-label')).toBeNull();
expect(screen.getByText('rightSidebar.review.fileCount 5')).toBeTruthy();
});
it('toggles rich markdown preview from the diff list header', () => {
const onRichMarkdownPreviewChange = vi.fn();
- render(createElement(ReviewDiffListHeader, {
- fileCount: 1,
- refreshPending: false,
- onRefresh: vi.fn(),
- viewMode: 'unified',
- onViewModeChange: vi.fn(),
- richMarkdownPreview: false,
- onRichMarkdownPreviewChange,
- }));
-
- const button = screen.getByRole('button', { name: 'rightSidebar.review.moreMenu.richPreviewEnable' });
+ render(
+ createElement(ReviewDiffListHeader, {
+ fileCount: 1,
+ refreshPending: false,
+ onRefresh: vi.fn(),
+ viewMode: 'unified',
+ onViewModeChange: vi.fn(),
+ richMarkdownPreview: false,
+ onRichMarkdownPreviewChange,
+ }),
+ );
+
+ const button = screen.getByRole('button', {
+ name: 'rightSidebar.review.moreMenu.richPreviewEnable',
+ });
expect(button.getAttribute('aria-pressed')).toBe('false');
expect(button.querySelector('.lucide-image-off')).toBeTruthy();
fireEvent.click(button);
@@ -499,16 +593,34 @@ describe('ReviewTabBody commit source guards', () => {
expect(shouldFallbackFromMissingSelectedCommit('commit', 'missing', commits, true)).toBe(true);
expect(shouldFallbackFromMissingSelectedCommit('commit', 'a', commits, true)).toBe(false);
- expect(shouldFallbackFromMissingSelectedCommit('commit', 'missing', commits, false)).toBe(false);
- expect(shouldFallbackFromMissingSelectedCommit('commit', 'missing', commits, true, true)).toBe(false);
- expect(shouldFallbackFromMissingSelectedCommit('branch' as ReviewSource, 'missing', commits, true)).toBe(false);
+ expect(shouldFallbackFromMissingSelectedCommit('commit', 'missing', commits, false)).toBe(
+ false,
+ );
+ expect(shouldFallbackFromMissingSelectedCommit('commit', 'missing', commits, true, true)).toBe(
+ false,
+ );
+ expect(
+ shouldFallbackFromMissingSelectedCommit('branch' as ReviewSource, 'missing', commits, true),
+ ).toBe(false);
expect(shouldFallbackFromMissingSelectedCommit('commit', null, commits, true)).toBe(false);
});
it('keeps the newly committed selection while commits refresh and after it appears in the refreshed list', () => {
- expect(shouldFallbackFromMissingSelectedCommit('commit', 'new', [{ oid: 'old' }], true, true)).toBe(false);
- expect(shouldFallbackFromMissingSelectedCommit('commit', 'new', [{ oid: 'new' }, { oid: 'old' }], true, false)).toBe(false);
- expect(shouldFallbackFromMissingSelectedCommit('commit', 'new', [{ oid: 'old' }], true, false)).toBe(true);
+ expect(
+ shouldFallbackFromMissingSelectedCommit('commit', 'new', [{ oid: 'old' }], true, true),
+ ).toBe(false);
+ expect(
+ shouldFallbackFromMissingSelectedCommit(
+ 'commit',
+ 'new',
+ [{ oid: 'new' }, { oid: 'old' }],
+ true,
+ false,
+ ),
+ ).toBe(false);
+ expect(
+ shouldFallbackFromMissingSelectedCommit('commit', 'new', [{ oid: 'old' }], true, false),
+ ).toBe(true);
});
});
@@ -565,10 +677,12 @@ describe('ReviewTabBody operation notices', () => {
describe('ReviewTabBody hover-reveal action affordance', () => {
it('keeps file actions visible without waiting for hover or focus', () => {
- render(createElement('div', {
- 'data-testid': 'file-actions',
- className: reviewActionRevealClass('file', false),
- }));
+ render(
+ createElement('div', {
+ 'data-testid': 'file-actions',
+ className: reviewActionRevealClass('file', false),
+ }),
+ );
const actions = screen.getByTestId('file-actions');
expect(actions.className).toContain('visible');
@@ -611,24 +725,36 @@ describe('ReviewTabBody hover-reveal action affordance', () => {
onHunkAction: vi.fn(),
onSectionAction: vi.fn(),
};
- const { container, rerender } = render(createElement(BatchActionPill, {
- allPending: false,
- discardAllPending: false,
- writeAction: unstagedActions,
- }));
+ const { container, rerender } = render(
+ createElement(BatchActionPill, {
+ allPending: false,
+ discardAllPending: false,
+ writeAction: unstagedActions,
+ }),
+ );
expect(container.querySelector('[data-review-batch-action-pill="true"]')).toBeTruthy();
- expect(screen.getByRole('button', { name: 'rightSidebar.review.actions.discardAll' })).toBeTruthy();
- expect(screen.getByRole('button', { name: 'rightSidebar.review.actions.stageAll' })).toBeTruthy();
-
- rerender(createElement(BatchActionPill, {
- allPending: false,
- discardAllPending: false,
- writeAction: stagedActions,
- }));
-
- expect(screen.queryByRole('button', { name: 'rightSidebar.review.actions.discardAll' })).toBeNull();
- expect(screen.getByRole('button', { name: 'rightSidebar.review.actions.unstageAll' })).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.review.actions.discardAll' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.review.actions.stageAll' }),
+ ).toBeTruthy();
+
+ rerender(
+ createElement(BatchActionPill, {
+ allPending: false,
+ discardAllPending: false,
+ writeAction: stagedActions,
+ }),
+ );
+
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.review.actions.discardAll' }),
+ ).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.review.actions.unstageAll' }),
+ ).toBeTruthy();
});
it('keeps narrow batch actions icon-only with tooltips and a max-width guard', () => {
@@ -648,98 +774,122 @@ describe('ReviewTabBody hover-reveal action affordance', () => {
onSectionAction: vi.fn(),
onSectionDiscard: vi.fn(),
};
- const { container } = render(createElement(BatchActionPill, {
- allPending: true,
- discardAllPending: false,
- layout: 'icon-only',
- writeAction: unstagedActions,
- }));
+ const { container } = render(
+ createElement(BatchActionPill, {
+ allPending: true,
+ discardAllPending: false,
+ layout: 'icon-only',
+ writeAction: unstagedActions,
+ }),
+ );
const pill = container.querySelector<HTMLElement>('[data-review-batch-action-pill="true"]');
expect(pill?.style.maxWidth).toBe('calc(100% - 16px)');
- const stageButton = screen.getByRole('button', { name: 'rightSidebar.review.actions.stageAll' });
+ const stageButton = screen.getByRole('button', {
+ name: 'rightSidebar.review.actions.stageAll',
+ });
expect(stageButton.className).toContain('w-6');
- expect(stageButton.querySelector('.sr-only')?.textContent).toBe('rightSidebar.review.actions.stageAll');
+ expect(stageButton.querySelector('.sr-only')?.textContent).toBe(
+ 'rightSidebar.review.actions.stageAll',
+ );
expect(stageButton.querySelector('.animate-spin')).toBeTruthy();
});
});
describe('ReviewTabBody commit dropdown enablement', () => {
it('requires a message before evaluating change availability', () => {
- expect(getReviewCommitActionDisabledReason({
- message: ' ',
- includeUnstaged: true,
- stagedCount: 1,
- unstagedCount: 1,
- canWrite: true,
- })).toBe('no-message');
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: ' ',
+ includeUnstaged: true,
+ stagedCount: 1,
+ unstagedCount: 1,
+ canWrite: true,
+ }),
+ ).toBe('no-message');
});
it('allows committing any dirty state when unstaged changes are included', () => {
- expect(getReviewCommitActionDisabledReason({
- message: 'ship it',
- includeUnstaged: true,
- stagedCount: 0,
- unstagedCount: 1,
- canWrite: true,
- })).toBeNull();
- expect(getReviewCommitActionDisabledReason({
- message: 'ship it',
- includeUnstaged: true,
- stagedCount: 0,
- unstagedCount: 0,
- canWrite: true,
- })).toBe('no-changes');
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: 'ship it',
+ includeUnstaged: true,
+ stagedCount: 0,
+ unstagedCount: 1,
+ canWrite: true,
+ }),
+ ).toBeNull();
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: 'ship it',
+ includeUnstaged: true,
+ stagedCount: 0,
+ unstagedCount: 0,
+ canWrite: true,
+ }),
+ ).toBe('no-changes');
});
it('keeps staged-only commits gated on staged changes', () => {
- expect(getReviewCommitActionDisabledReason({
- message: 'ship it',
- includeUnstaged: false,
- stagedCount: 1,
- unstagedCount: 1,
- canWrite: true,
- })).toBeNull();
- expect(getReviewCommitActionDisabledReason({
- message: 'ship it',
- includeUnstaged: false,
- stagedCount: 0,
- unstagedCount: 1,
- canWrite: true,
- })).toBe('no-staged');
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: 'ship it',
+ includeUnstaged: false,
+ stagedCount: 1,
+ unstagedCount: 1,
+ canWrite: true,
+ }),
+ ).toBeNull();
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: 'ship it',
+ includeUnstaged: false,
+ stagedCount: 0,
+ unstagedCount: 1,
+ canWrite: true,
+ }),
+ ).toBe('no-staged');
});
it('honors write gates once the message exists', () => {
- expect(getReviewCommitActionDisabledReason({
- message: 'ship it',
- includeUnstaged: true,
- stagedCount: 1,
- unstagedCount: 0,
- canWrite: false,
- })).toBe('write-disabled');
+ expect(
+ getReviewCommitActionDisabledReason({
+ message: 'ship it',
+ includeUnstaged: true,
+ stagedCount: 1,
+ unstagedCount: 0,
+ canWrite: false,
+ }),
+ ).toBe('write-disabled');
});
it('clears a consumed commit message even when push fails after the commit', () => {
- expect(getReviewCommitDropdownCompletionEffect({
- committed: true,
- completed: false,
- })).toEqual({
+ expect(
+ getReviewCommitDropdownCompletionEffect({
+ committed: true,
+ completed: false,
+ }),
+ ).toEqual({
clearMessage: true,
closeDropdown: false,
});
- expect(getReviewCommitDropdownCompletionEffect({
- committed: true,
- completed: true,
- })).toEqual({
+ expect(
+ getReviewCommitDropdownCompletionEffect({
+ committed: true,
+ completed: true,
+ }),
+ ).toEqual({
clearMessage: true,
closeDropdown: true,
});
- expect(getReviewCommitDropdownCompletionEffect({
- committed: false,
- completed: false,
- })).toEqual({
+ expect(
+ getReviewCommitDropdownCompletionEffect({
+ committed: false,
+ completed: false,
+ }),
+ ).toEqual({
clearMessage: false,
closeDropdown: false,
});
@@ -763,26 +913,33 @@ describe('ReviewTabBody hidden whitespace helpers', () => {
it('hides only modified text diffs that have no hunks in whitespace-hidden mode', () => {
const whitespaceOnly = diff('unstaged', 'space.ts', { hunks: [] });
const substantive = diff('unstaged', 'code.ts', {
- hunks: [{
- index: 0,
- header: '@@ -1 +1 @@',
- oldStart: 1,
- oldLines: 1,
- newStart: 1,
- newLines: 1,
- section: '',
- lines: [],
- selectableLines: [],
- raw: '',
- }],
+ hunks: [
+ {
+ index: 0,
+ header: '@@ -1 +1 @@',
+ oldStart: 1,
+ oldLines: 1,
+ newStart: 1,
+ newLines: 1,
+ section: '',
+ lines: [],
+ selectableLines: [],
+ raw: '',
+ },
+ ],
});
const untracked = diff('unstaged', 'new.ts', { status: 'untracked', hunks: [] });
const binary = diff('unstaged', 'image.png', { kind: 'binary', hunks: [] });
expect(shouldHideWhitespaceOnlyDiff(whitespaceOnly, true)).toBe(true);
- expect(filterWhitespaceHiddenDiffs([whitespaceOnly, substantive, untracked, binary], true).map((item) => item.path))
- .toEqual(['code.ts', 'new.ts', 'image.png']);
- expect(filterWhitespaceHiddenDiffs([whitespaceOnly], false).map((item) => item.path)).toEqual(['space.ts']);
+ expect(
+ filterWhitespaceHiddenDiffs([whitespaceOnly, substantive, untracked, binary], true).map(
+ (item) => item.path,
+ ),
+ ).toEqual(['code.ts', 'new.ts', 'image.png']);
+ expect(filterWhitespaceHiddenDiffs([whitespaceOnly], false).map((item) => item.path)).toEqual([
+ 'space.ts',
+ ]);
});
it('keeps patch-based hunk actions available when whitespace is hidden', () => {
@@ -799,38 +956,48 @@ describe('ReviewTabBody capped diff helpers', () => {
totalChangedLines: 3,
totalChangedBytes: 20,
},
- files: [{
- id: 'branch:main:a.ts',
- source: 'branch' as const,
- path: 'a.ts',
- oldPath: null,
- status: 'modified' as const,
- additions: 2,
- deletions: 1,
- changedLines: 3,
- changedBytes: 20,
- isBinary: false,
- isSubmodule: false,
- }],
+ files: [
+ {
+ id: 'branch:main:a.ts',
+ source: 'branch' as const,
+ path: 'a.ts',
+ oldPath: null,
+ status: 'modified' as const,
+ additions: 2,
+ deletions: 1,
+ changedLines: 3,
+ changedBytes: 20,
+ isBinary: false,
+ isSubmodule: false,
+ },
+ ],
};
it('selects the capped payload for the active source', () => {
- expect(getCappedDiffForSource({
- source: 'branch',
- branchCapped: capped,
- })).toBe(capped);
- expect(getCappedDiffForSource({
- source: 'unstaged',
- worktreeCapped: { unstaged: capped, staged: null },
- })).toBe(capped);
- expect(getCappedDiffForSource({
- source: 'last-turn',
- worktreeCapped: { unstaged: capped, staged: null },
- })).toBeNull();
- expect(getCappedDiffForSource({
- source: 'last-turn',
- lastTurnCapped: capped,
- })).toBe(capped);
+ expect(
+ getCappedDiffForSource({
+ source: 'branch',
+ branchCapped: capped,
+ }),
+ ).toBe(capped);
+ expect(
+ getCappedDiffForSource({
+ source: 'unstaged',
+ worktreeCapped: { unstaged: capped, staged: null },
+ }),
+ ).toBe(capped);
+ expect(
+ getCappedDiffForSource({
+ source: 'last-turn',
+ worktreeCapped: { unstaged: capped, staged: null },
+ }),
+ ).toBeNull();
+ expect(
+ getCappedDiffForSource({
+ source: 'last-turn',
+ lastTurnCapped: capped,
+ }),
+ ).toBe(capped);
});
it('keeps the current capped file selection when it still exists and otherwise defaults to the first file', () => {
@@ -860,12 +1027,25 @@ describe('ReviewTabBody capped diff helpers', () => {
});
it('keeps mixed staged and unstaged Last turn subsets in normal mode when the subset is below capped thresholds', () => {
- const unstagedEntry = { ...capped.files[0], id: 'unstaged:small-a.ts', source: 'unstaged' as const, path: 'small-a.ts' };
- const stagedEntry = { ...capped.files[0], id: 'staged:small-b.ts', source: 'staged' as const, path: 'small-b.ts' };
- const entries = getLastTurnCappedSummaryEntries({
- unstaged: { ...capped, files: [unstagedEntry] },
- staged: { ...capped, files: [stagedEntry] },
- }, new Set(['small-a.ts', 'small-b.ts']));
+ const unstagedEntry = {
+ ...capped.files[0],
+ id: 'unstaged:small-a.ts',
+ source: 'unstaged' as const,
+ path: 'small-a.ts',
+ };
+ const stagedEntry = {
+ ...capped.files[0],
+ id: 'staged:small-b.ts',
+ source: 'staged' as const,
+ path: 'small-b.ts',
+ };
+ const entries = getLastTurnCappedSummaryEntries(
+ {
+ unstaged: { ...capped, files: [unstagedEntry] },
+ staged: { ...capped, files: [stagedEntry] },
+ },
+ new Set(['small-a.ts', 'small-b.ts']),
+ );
expect(entries.map((entry) => `${entry.source}:${entry.path}`)).toEqual([
'unstaged:small-a.ts',
@@ -884,10 +1064,15 @@ describe('ReviewTabBody capped diff helpers', () => {
status: 'renamed' as const,
};
- expect(getLastTurnCappedSummaryEntries({
- unstaged: null,
- staged: { ...capped, files: [renamed] },
- }, new Set(['renamed-old.ts']))).toEqual([renamed]);
+ expect(
+ getLastTurnCappedSummaryEntries(
+ {
+ unstaged: null,
+ staged: { ...capped, files: [renamed] },
+ },
+ new Set(['renamed-old.ts']),
+ ),
+ ).toEqual([renamed]);
});
it('keeps Last turn in capped mode when the narrowed subset still exceeds thresholds', () => {
@@ -910,29 +1095,31 @@ describe('ReviewTabBody capped diff helpers', () => {
it('keeps capped views inside the same flex source frame as normal source views', () => {
const summaryDiff = summaryEntryToPlaceholderDiff(capped.files[0]);
- const { container } = render(createElement(CappedSourceView, {
- capped,
- summaryDiffs: [summaryDiff],
- selectedSummaryDiff: null,
- loadedDiff: null,
- loading: false,
- error: null,
- onSelectFile: vi.fn(),
- onRefresh: vi.fn(),
- refreshPending: false,
- viewMode: 'unified',
- onViewModeChange: vi.fn(),
- onRichMarkdownPreviewChange: vi.fn(),
- wordWrap: false,
- wordDiff: true,
- expandedSet: new Set<string>(),
- onToggleDiff: vi.fn(),
- fileTreeVisible: true,
- loadImagePreview: vi.fn(),
- loadMarkdownPreview: vi.fn(),
- richMarkdownPreview: true,
- onOpenFile: vi.fn(),
- }));
+ const { container } = render(
+ createElement(CappedSourceView, {
+ capped,
+ summaryDiffs: [summaryDiff],
+ selectedSummaryDiff: null,
+ loadedDiff: null,
+ loading: false,
+ error: null,
+ onSelectFile: vi.fn(),
+ onRefresh: vi.fn(),
+ refreshPending: false,
+ viewMode: 'unified',
+ onViewModeChange: vi.fn(),
+ onRichMarkdownPreviewChange: vi.fn(),
+ wordWrap: false,
+ wordDiff: true,
+ expandedSet: new Set<string>(),
+ onToggleDiff: vi.fn(),
+ fileTreeVisible: true,
+ loadImagePreview: vi.fn(),
+ loadMarkdownPreview: vi.fn(),
+ richMarkdownPreview: true,
+ onOpenFile: vi.fn(),
+ }),
+ );
const frame = container.firstElementChild as HTMLElement | null;
expect(frame?.dataset.testid).toBe('review-capped-source-view');
@@ -947,57 +1134,61 @@ describe('ReviewTabBody capped diff helpers', () => {
it('uses the selected capped file expansion state for the single rendered file', () => {
const summaryDiff = summaryEntryToPlaceholderDiff(capped.files[0]);
const toggle = vi.fn();
- const { rerender } = render(createElement(CappedSourceView, {
- capped,
- summaryDiffs: [summaryDiff],
- selectedSummaryDiff: summaryDiff,
- loadedDiff: summaryDiff,
- loading: false,
- error: null,
- onSelectFile: vi.fn(),
- onRefresh: vi.fn(),
- refreshPending: false,
- viewMode: 'unified',
- onViewModeChange: vi.fn(),
- onRichMarkdownPreviewChange: vi.fn(),
- wordWrap: false,
- wordDiff: true,
- expandedSet: new Set([summaryDiff.id]),
- onToggleDiff: toggle,
- fileTreeVisible: false,
- loadImagePreview: vi.fn(),
- loadMarkdownPreview: vi.fn(),
- richMarkdownPreview: true,
- onOpenFile: vi.fn(),
- }));
+ const { rerender } = render(
+ createElement(CappedSourceView, {
+ capped,
+ summaryDiffs: [summaryDiff],
+ selectedSummaryDiff: summaryDiff,
+ loadedDiff: summaryDiff,
+ loading: false,
+ error: null,
+ onSelectFile: vi.fn(),
+ onRefresh: vi.fn(),
+ refreshPending: false,
+ viewMode: 'unified',
+ onViewModeChange: vi.fn(),
+ onRichMarkdownPreviewChange: vi.fn(),
+ wordWrap: false,
+ wordDiff: true,
+ expandedSet: new Set([summaryDiff.id]),
+ onToggleDiff: toggle,
+ fileTreeVisible: false,
+ loadImagePreview: vi.fn(),
+ loadMarkdownPreview: vi.fn(),
+ richMarkdownPreview: true,
+ onOpenFile: vi.fn(),
+ }),
+ );
const button = screen.getByRole('button', { expanded: true });
fireEvent.click(button);
expect(toggle).toHaveBeenCalledWith(summaryDiff.id);
- rerender(createElement(CappedSourceView, {
- capped,
- summaryDiffs: [summaryDiff],
- selectedSummaryDiff: summaryDiff,
- loadedDiff: summaryDiff,
- loading: false,
- error: null,
- onSelectFile: vi.fn(),
- onRefresh: vi.fn(),
- refreshPending: false,
- viewMode: 'unified',
- onViewModeChange: vi.fn(),
- onRichMarkdownPreviewChange: vi.fn(),
- wordWrap: false,
- wordDiff: true,
- expandedSet: new Set<string>(),
- onToggleDiff: toggle,
- fileTreeVisible: false,
- loadImagePreview: vi.fn(),
- loadMarkdownPreview: vi.fn(),
- richMarkdownPreview: true,
- onOpenFile: vi.fn(),
- }));
+ rerender(
+ createElement(CappedSourceView, {
+ capped,
+ summaryDiffs: [summaryDiff],
+ selectedSummaryDiff: summaryDiff,
+ loadedDiff: summaryDiff,
+ loading: false,
+ error: null,
+ onSelectFile: vi.fn(),
+ onRefresh: vi.fn(),
+ refreshPending: false,
+ viewMode: 'unified',
+ onViewModeChange: vi.fn(),
+ onRichMarkdownPreviewChange: vi.fn(),
+ wordWrap: false,
+ wordDiff: true,
+ expandedSet: new Set<string>(),
+ onToggleDiff: toggle,
+ fileTreeVisible: false,
+ loadImagePreview: vi.fn(),
+ loadMarkdownPreview: vi.fn(),
+ richMarkdownPreview: true,
+ onOpenFile: vi.fn(),
+ }),
+ );
expect(screen.getByRole('button', { expanded: false })).toBeTruthy();
expect(screen.queryByText('rightSidebar.review.noRenderableDiff')).toBeNull();
@@ -1048,10 +1239,12 @@ describe('ReviewTabBody capped diff helpers', () => {
container.scrollTop = 10;
const scrollTo = vi.fn();
container.scrollTo = scrollTo;
- const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback: FrameRequestCallback) => {
- callback(0);
- return 1;
- });
+ const rafSpy = vi
+ .spyOn(window, 'requestAnimationFrame')
+ .mockImplementation((callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ });
vi.spyOn(container, 'getBoundingClientRect').mockReturnValue({
x: 0,
y: 100,
@@ -1077,16 +1270,18 @@ describe('ReviewTabBody capped diff helpers', () => {
revealReviewFileTreeActiveNode({
activeFileId: 'unstaged:src/deep.ts',
- flatNodes: [{
- depth: 1,
- node: {
- type: 'file',
- id: 'unstaged:src/deep.ts',
- path: 'src/deep.ts',
- name: 'deep.ts',
- diff: diff('unstaged', 'src/deep.ts'),
+ flatNodes: [
+ {
+ depth: 1,
+ node: {
+ type: 'file',
+ id: 'unstaged:src/deep.ts',
+ path: 'src/deep.ts',
+ name: 'deep.ts',
+ diff: diff('unstaged', 'src/deep.ts'),
+ },
},
- }],
+ ],
virtualized: false,
treeVirtualizer: { scrollToIndex: vi.fn() },
listEl: container,
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.ts
index 8587238bd2..efe5ae7279 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
@@ -37,8 +37,30 @@ describe('review plugin', () => {
it('defaultState returns fresh collapsedPaths array per call', () => {
const p = registry.getTabKind('review')!;
- const a = p.defaultState() as { collapsedPaths: string[]; diffViewMode: string; fileTreeVisible: boolean; wordWrap: boolean; wordDiff: boolean; hideWhitespace: boolean; richMarkdownPreview: boolean; branchBaseRef: string | null };
- const b = p.defaultState() as { collapsedPaths: string[]; diffViewMode: string; fileTreeVisible: boolean; wordWrap: boolean; wordDiff: boolean; hideWhitespace: boolean; richMarkdownPreview: boolean; branchBaseRef: string | null };
+ const a = p.defaultState() as {
+ descriptor: { kind: string };
+ 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[];
+ diffViewMode: string;
+ fileTreeVisible: boolean;
+ wordWrap: boolean;
+ wordDiff: boolean;
+ hideWhitespace: boolean;
+ richMarkdownPreview: boolean;
+ };
+ expect(a.descriptor).toEqual({ kind: 'unstaged' });
+ expect(a.jumpTarget).toBeNull();
expect(a.collapsedPaths).toEqual([]);
expect(b.collapsedPaths).toEqual([]);
expect(a.diffViewMode).toBe('unified');
@@ -47,7 +69,6 @@ describe('review plugin', () => {
expect(a.wordDiff).toBe(false);
expect(a.hideWhitespace).toBe(false);
expect(a.richMarkdownPreview).toBe(true);
- expect(a.branchBaseRef).toBeNull();
// 不要让多个 tab 共享同一个数组引用 → mutate a 不影响 b
a.collapsedPaths.push('whatever');
expect(b.collapsedPaths).toEqual([]);
@@ -64,7 +85,8 @@ describe('review plugin', () => {
wordDiff: false,
hideWhitespace: true,
richMarkdownPreview: false,
- branchBaseRef: 'main',
+ descriptor: { kind: 'branch', baseRef: 'main' },
+ jumpTarget: { diffId: 'branch:main:a.ts', path: 'a.ts', nonce: 3 },
}) as {
collapsedPaths: string[];
diffViewMode: string;
@@ -73,7 +95,8 @@ describe('review plugin', () => {
wordDiff: boolean;
hideWhitespace: boolean;
richMarkdownPreview: boolean;
- branchBaseRef: string | null;
+ 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.diffViewMode).toBe('split');
@@ -82,16 +105,85 @@ describe('review plugin', () => {
expect(s.wordDiff).toBe(false);
expect(s.hideWhitespace).toBe(true);
expect(s.richMarkdownPreview).toBe(false);
- expect(s.branchBaseRef).toBe('main');
+ expect(s.descriptor).toEqual({ kind: 'branch', baseRef: 'main' });
+ expect(s.jumpTarget).toEqual({ diffId: 'branch:main:a.ts', path: 'a.ts', nonce: 3 });
});
- it('hydrateState keeps a valid session-level branch base ref and drops invalid values', () => {
+ it('hydrateState keeps a safe branch descriptor and fails closed on invalid refs', () => {
const p = registry.getTabKind('review')!;
- expect((p.hydrateState!({ branchBaseRef: 'origin/main' }) as { branchBaseRef: string | null }).branchBaseRef).toBe('origin/main');
- expect((p.hydrateState!({ branchBaseRef: '' }) as { branchBaseRef: string | null }).branchBaseRef).toBeNull();
- expect((p.hydrateState!({ branchBaseRef: '-bad' }) as { branchBaseRef: string | null }).branchBaseRef).toBeNull();
- expect((p.hydrateState!({ branchBaseRef: 'main~1' }) as { branchBaseRef: string | null }).branchBaseRef).toBeNull();
- expect((p.hydrateState!({ branchBaseRef: 42 }) as { branchBaseRef: string | null }).branchBaseRef).toBeNull();
+ expect(
+ (
+ p.hydrateState!({ descriptor: { kind: 'branch', baseRef: 'origin/main' } }) as {
+ descriptor: unknown;
+ }
+ ).descriptor,
+ ).toEqual({ kind: 'branch', baseRef: 'origin/main' });
+ expect(
+ (
+ p.hydrateState!({ descriptor: { kind: 'branch', baseRef: '-bad' } }) as {
+ descriptor: unknown;
+ }
+ ).descriptor,
+ ).toEqual({ kind: 'unstaged' });
+ expect(
+ (
+ p.hydrateState!({ descriptor: { kind: 'branch', baseRef: 'main~1' } }) as {
+ descriptor: unknown;
+ }
+ ).descriptor,
+ ).toEqual({ kind: 'unstaged' });
+ expect(
+ (p.hydrateState!({ descriptor: { kind: 'branch', baseRef: 42 } }) as { descriptor: unknown })
+ .descriptor,
+ ).toEqual({ kind: 'unstaged' });
+ });
+
+ it('migrates the legacy turnTarget into descriptor and jumpTarget once', () => {
+ const p = registry.getTabKind('review')!;
+ const state = p.hydrateState!({
+ turnTarget: {
+ changeSetIds: ['set-1', 'set-2'],
+ selectedDiffId: 'unstaged:src/a.ts',
+ selectedPath: 'src/a.ts',
+ requestNonce: 9,
+ targetSessionId: 'worker-session',
+ },
+ }) as { descriptor: unknown; jumpTarget: unknown };
+
+ expect(state.descriptor).toEqual({
+ kind: 'turn-set',
+ changeSetIds: ['set-1', 'set-2'],
+ targetSessionId: 'worker-session',
+ });
+ expect(state.jumpTarget).toEqual({
+ diffId: 'unstaged:src/a.ts',
+ path: 'src/a.ts',
+ nonce: 9,
+ });
+ });
+
+ it('does not mix a stale legacy jump into a persisted descriptor', () => {
+ const p = registry.getTabKind('review')!;
+ const state = p.hydrateState!({
+ descriptor: {
+ kind: 'turn-set',
+ targetSessionId: 'current-worker',
+ changeSetIds: ['current-set'],
+ },
+ turnTarget: {
+ targetSessionId: 'stale-worker',
+ changeSetIds: ['stale-set'],
+ selectedPath: 'stale.ts',
+ requestNonce: 4,
+ },
+ }) as { descriptor: unknown; jumpTarget: unknown };
+
+ expect(state.descriptor).toEqual({
+ kind: 'turn-set',
+ targetSessionId: 'current-worker',
+ changeSetIds: ['current-set'],
+ });
+ expect(state.jumpTarget).toBeNull();
});
it('hydrateState falls back to disabled word wrap for invalid values', () => {
@@ -111,30 +203,39 @@ describe('review plugin', () => {
it('hydrateState falls back to visible whitespace changes for invalid values', () => {
const p = registry.getTabKind('review')!;
- expect((p.hydrateState!({ hideWhitespace: true }) as { hideWhitespace: boolean }).hideWhitespace).toBe(true);
- expect((p.hydrateState!({ hideWhitespace: 'yes' }) as { hideWhitespace: boolean }).hideWhitespace).toBe(false);
+ expect(
+ (p.hydrateState!({ hideWhitespace: true }) as { hideWhitespace: boolean }).hideWhitespace,
+ ).toBe(true);
+ expect(
+ (p.hydrateState!({ hideWhitespace: 'yes' }) as { hideWhitespace: boolean }).hideWhitespace,
+ ).toBe(false);
expect((p.hydrateState!({}) as { hideWhitespace: boolean }).hideWhitespace).toBe(false);
});
it('hydrateState defaults rich markdown preview to enabled for invalid values', () => {
const p = registry.getTabKind('review')!;
- expect((p.hydrateState!({ richMarkdownPreview: false }) as { richMarkdownPreview: boolean }).richMarkdownPreview).toBe(false);
- expect((p.hydrateState!({ richMarkdownPreview: true }) as { richMarkdownPreview: boolean }).richMarkdownPreview).toBe(true);
- expect((p.hydrateState!({ richMarkdownPreview: 'yes' }) as { richMarkdownPreview: boolean }).richMarkdownPreview).toBe(true);
- expect((p.hydrateState!({}) as { richMarkdownPreview: boolean }).richMarkdownPreview).toBe(true);
+ expect(
+ (p.hydrateState!({ richMarkdownPreview: false }) as { richMarkdownPreview: boolean })
+ .richMarkdownPreview,
+ ).toBe(false);
+ expect(
+ (p.hydrateState!({ richMarkdownPreview: true }) as { richMarkdownPreview: boolean })
+ .richMarkdownPreview,
+ ).toBe(true);
+ expect(
+ (p.hydrateState!({ richMarkdownPreview: 'yes' }) as { richMarkdownPreview: boolean })
+ .richMarkdownPreview,
+ ).toBe(true);
+ expect((p.hydrateState!({}) as { richMarkdownPreview: boolean }).richMarkdownPreview).toBe(
+ true,
+ );
});
it('hydrateState falls back to empty when raw is null / 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 { collapsedPaths: string[] }).collapsedPaths).toEqual([]);
+ expect((p.hydrateState!('garbage') as { collapsedPaths: string[] }).collapsedPaths).toEqual([]);
+ expect((p.hydrateState!({}) as { collapsedPaths: string[] }).collapsedPaths).toEqual([]);
expect(
(p.hydrateState!({ collapsedPaths: 'not-an-array' }) as { collapsedPaths: string[] })
.collapsedPaths,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts
new file mode 100644
index 0000000000..bc003652e5
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/useReviewSource.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment jsdom
+
+import { renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FileDiff } from '@/lib/gitReview.types';
+
+const mocks = vi.hoisted(() => ({
+ useReviewGitState: vi.fn(),
+ useReviewCommitDiff: vi.fn(),
+ useReviewBranchDiff: vi.fn(),
+ useReviewFileDiffs: vi.fn(),
+ useLastTurnFilter: vi.fn(),
+ getTurnChangeSets: vi.fn(),
+}));
+
+vi.mock('../useReviewGitState', () => ({
+ useReviewGitState: mocks.useReviewGitState,
+ useReviewCommitDiff: mocks.useReviewCommitDiff,
+ useReviewBranchDiff: mocks.useReviewBranchDiff,
+ useReviewFileDiffs: mocks.useReviewFileDiffs,
+}));
+
+vi.mock('../useLastTurnFilter', () => ({
+ useLastTurnFilter: mocks.useLastTurnFilter,
+}));
+
+import { REVIEW_TURN_LOCAL_ONLY_ERROR, useReviewSource } from '../useReviewSource';
+
+function loadState<T>(data: T | null = null) {
+ return {
+ data,
+ loading: false,
+ error: null,
+ errorCode: null,
+ refresh: vi.fn(),
+ setData: vi.fn(),
+ };
+}
+
+function diff(path: string): FileDiff {
+ return {
+ id: `unstaged:${path}`,
+ source: 'unstaged',
+ path,
+ oldPath: null,
+ status: 'modified',
+ kind: 'text',
+ size: 10,
+ additions: 1,
+ deletions: 0,
+ isBinary: false,
+ isSubmodule: false,
+ isTooLarge: false,
+ mode: { old: null, new: null },
+ index: { oldOid: null, newOid: null },
+ rawHeader: '',
+ rawPatch: '',
+ hunks: [],
+ error: null,
+ };
+}
+
+describe('useReviewSource', () => {
+ beforeEach(() => {
+ mocks.useReviewGitState.mockReturnValue(loadState());
+ mocks.useReviewCommitDiff.mockReturnValue(loadState());
+ mocks.useReviewBranchDiff.mockReturnValue(loadState());
+ mocks.useReviewFileDiffs.mockReturnValue(loadState([]));
+ mocks.useLastTurnFilter.mockReturnValue(new Set<string>());
+ mocks.getTurnChangeSets.mockReset();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { getTurnChangeSets: mocks.getTurnChangeSets } },
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('loads a turn-set through the historical source and skips every git source hook', async () => {
+ const recordedDiff = diff('src/a.ts');
+ mocks.getTurnChangeSets.mockResolvedValue([
+ {
+ id: 'set-1',
+ state: 'partial',
+ diffs: [recordedDiff],
+ },
+ ]);
+
+ const { result } = renderHook(() =>
+ useReviewSource(
+ { kind: 'turn-set', targetSessionId: 'worker-session', changeSetIds: ['set-1'] },
+ 'host-session',
+ { hideWhitespace: false, deviceLinkDeviceId: null, remoteHostId: null },
+ ),
+ );
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(mocks.getTurnChangeSets).toHaveBeenCalledWith('worker-session', ['set-1']);
+ expect(result.current.diffs).toEqual([recordedDiff]);
+ expect(result.current.isPartial).toBe(true);
+ expect(mocks.useReviewGitState).toHaveBeenCalledWith(null, false, null);
+ expect(mocks.useReviewCommitDiff).toHaveBeenCalledWith(null, null, false, null);
+ expect(mocks.useReviewBranchDiff).toHaveBeenCalledWith(null, null, false, false, null);
+ });
+
+ it('fails closed for remote historical snapshots without calling the local IPC', async () => {
+ const { result } = renderHook(() =>
+ useReviewSource(
+ { kind: 'turn-set', targetSessionId: null, changeSetIds: ['set-1'] },
+ 'host-session',
+ { hideWhitespace: false, deviceLinkDeviceId: null, remoteHostId: 'ssh-host' },
+ ),
+ );
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.error).toBe(REVIEW_TURN_LOCAL_ONLY_ERROR);
+ expect(mocks.getTurnChangeSets).not.toHaveBeenCalled();
+ });
+});
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.tsx
index f9d268ea44..c9284dee69 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
@@ -1,8 +1,8 @@
/**
- * review plugin —— RSB 内显示"本次会话改动了哪些文件"的常驻 tab。
+ * review plugin —— RSB 内统一显示当前 Git 状态与消息级历史变更的常驻 tab。
*
- * 数据从 git-review IPC 派生;makerChatStore 只提供 Last turn 过滤集合。plugin
- * 自身持久化用户收起过哪些 diff id(`collapsedPaths`)、diff 模式、文件树显隐、
+ * 数据源由可持久化 descriptor 选择;Git 来源走 git-review IPC,历史来源读取
+ * 已记录的 turn change sets。plugin 自身持久化用户收起过哪些 diff id(`collapsedPaths`)、diff 模式、文件树显隐、
* diff 自动换行偏好、文字差异偏好、隐藏空白变更偏好、Markdown 富文本预览偏好与分支来源的基准分支。
*
* 单例语义 —— 由 RightSidebarShell + AddTabDropdown 在调用层用
@@ -16,7 +16,13 @@ import { lazy } from 'react';
import { FileDiff } from 'lucide-react';
import type { TFunction } from 'i18next';
-import { isSafeBranchBaseRef } from '../../../../../shared/reviewBranchRef';
+import {
+ migrateLegacyTurnTarget,
+ parseReviewJumpTarget,
+ parseReviewSourceDescriptor,
+ type ReviewJumpTarget,
+ type ReviewSourceDescriptor,
+} from '../../../../../shared/reviewSource';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
import type { DiffViewMode } from './DiffViewer/PlainUnifiedDiff';
@@ -26,19 +32,10 @@ const ReviewTabBody = lazy(() =>
);
export interface ReviewState {
- /** Programmatic exact-turn review target. Null keeps the normal Git-backed review surface. */
- turnTarget: {
- changeSetIds: string[];
- selectedDiffId: string | null;
- selectedPath: string | null;
- requestNonce: number;
- /**
- * 变更集所属会话。null(旧数据)= 与 tab 桶同会话;与桶会话不同(协同面板
- * 里审查 worker 的轮次)时按它取数,且不提供 git 来源切换(git 视图跟随桶
- * 会话的 workdir,对 worker 语义错误)。
- */
- targetSessionId: string | null;
- } | null;
+ /** Persisted discriminated source; all review entry points write the same field. */
+ descriptor: ReviewSourceDescriptor;
+ /** Optional one-shot positioning request supplied by a review entry point. */
+ jumpTarget: ReviewJumpTarget | null;
/** 用户收起过哪些 diff id。空数组表示所有当前 diff 默认展开。 */
collapsedPaths: string[];
/** diff 展示模式。写操作仍回到原始 unified DiffLine.index。 */
@@ -53,12 +50,11 @@ export interface ReviewState {
hideWhitespace: boolean;
/** Markdown 文件是否默认用富文本预览替换 diff 主体。对齐 Codex,默认开启。 */
richMarkdownPreview: boolean;
- /** Branch source 的用户选择基准。首版按 tab/session 记住,不做 per-repo。 */
- branchBaseRef: string | null;
}
const DEFAULT_STATE: ReviewState = {
- turnTarget: null,
+ descriptor: { kind: 'unstaged' },
+ jumpTarget: null,
collapsedPaths: [],
diffViewMode: 'unified',
fileTreeVisible: false,
@@ -66,7 +62,6 @@ const DEFAULT_STATE: ReviewState = {
wordDiff: false,
hideWhitespace: false,
richMarkdownPreview: true,
- branchBaseRef: null,
};
function ReviewTabPillTitle({ t }: { state: ReviewState; t: TFunction }) {
@@ -100,47 +95,37 @@ const plugin: TabKindPlugin<ReviewState> = {
? obj.collapsedPaths.filter((s): s is string => typeof s === 'string')
: [];
const diffViewMode = obj.diffViewMode === 'split' ? 'split' : 'unified';
- const fileTreeVisible = typeof obj.fileTreeVisible === 'boolean'
- ? obj.fileTreeVisible
- : DEFAULT_STATE.fileTreeVisible;
- const wordWrap = typeof obj.wordWrap === 'boolean'
- ? obj.wordWrap
- : DEFAULT_STATE.wordWrap;
- const wordDiff = typeof obj.wordDiff === 'boolean'
- ? obj.wordDiff
- : DEFAULT_STATE.wordDiff;
- const hideWhitespace = typeof obj.hideWhitespace === 'boolean'
- ? obj.hideWhitespace
- : DEFAULT_STATE.hideWhitespace;
- const richMarkdownPreview = typeof obj.richMarkdownPreview === 'boolean'
- ? obj.richMarkdownPreview
- : DEFAULT_STATE.richMarkdownPreview;
- const branchBaseRef = typeof obj.branchBaseRef === 'string' && isSafeBranchBaseRef(obj.branchBaseRef.trim())
- ? obj.branchBaseRef.trim()
- : null;
- const rawTurnTarget = obj.turnTarget;
- const turnTarget = rawTurnTarget && typeof rawTurnTarget === 'object'
- && Array.isArray((rawTurnTarget as { changeSetIds?: unknown }).changeSetIds)
- && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.length > 0
- && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.length <= 16
- && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.every((id) => typeof id === 'string')
- ? {
- changeSetIds: (rawTurnTarget as { changeSetIds: string[] }).changeSetIds,
- selectedDiffId: typeof (rawTurnTarget as { selectedDiffId?: unknown }).selectedDiffId === 'string'
- ? (rawTurnTarget as { selectedDiffId: string }).selectedDiffId
- : null,
- selectedPath: typeof (rawTurnTarget as { selectedPath?: unknown }).selectedPath === 'string'
- ? (rawTurnTarget as { selectedPath: string }).selectedPath
- : null,
- requestNonce: typeof (rawTurnTarget as { requestNonce?: unknown }).requestNonce === 'number'
- ? (rawTurnTarget as { requestNonce: number }).requestNonce
- : 0,
- targetSessionId: typeof (rawTurnTarget as { targetSessionId?: unknown }).targetSessionId === 'string'
- ? (rawTurnTarget as { targetSessionId: string }).targetSessionId
- : null,
- }
- : null;
- return { turnTarget, collapsedPaths, diffViewMode, fileTreeVisible, wordWrap, wordDiff, hideWhitespace, richMarkdownPreview, branchBaseRef };
+ const fileTreeVisible =
+ typeof obj.fileTreeVisible === 'boolean'
+ ? obj.fileTreeVisible
+ : DEFAULT_STATE.fileTreeVisible;
+ const wordWrap = typeof obj.wordWrap === 'boolean' ? obj.wordWrap : DEFAULT_STATE.wordWrap;
+ const wordDiff = typeof obj.wordDiff === 'boolean' ? obj.wordDiff : DEFAULT_STATE.wordDiff;
+ const hideWhitespace =
+ typeof obj.hideWhitespace === 'boolean' ? obj.hideWhitespace : DEFAULT_STATE.hideWhitespace;
+ const richMarkdownPreview =
+ typeof obj.richMarkdownPreview === 'boolean'
+ ? obj.richMarkdownPreview
+ : DEFAULT_STATE.richMarkdownPreview;
+ const legacyTurnTarget = migrateLegacyTurnTarget(obj.turnTarget);
+ const persistedDescriptor = parseReviewSourceDescriptor(obj.descriptor);
+ const descriptor = persistedDescriptor ?? legacyTurnTarget?.descriptor ?? { kind: 'unstaged' };
+ const jumpTarget =
+ parseReviewJumpTarget(obj.jumpTarget) ??
+ (!persistedDescriptor && descriptor.kind === 'turn-set'
+ ? (legacyTurnTarget?.jumpTarget ?? null)
+ : null);
+ return {
+ descriptor,
+ jumpTarget,
+ collapsedPaths,
+ diffViewMode,
+ fileTreeVisible,
+ wordWrap,
+ wordDiff,
+ hideWhitespace,
+ richMarkdownPreview,
+ };
},
};
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts
new file mode 100644
index 0000000000..5bec429019
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts
@@ -0,0 +1,369 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+
+import type {
+ FileDiff,
+ ReviewBranchDiffData,
+ ReviewCappedDiffData,
+ ReviewCommitDiffData,
+ ReviewData,
+ ReviewDiffSummaryEntry,
+ ReviewFileDiffRequest,
+} from '@/lib/gitReview.types';
+import { extractIpcError } from '@/utils/ipcError';
+import { buildCappedDiffData } from '../../../../../shared/gitReviewCapped';
+import type { ReviewSourceDescriptor } from '../../../../../shared/reviewSource';
+import type { TurnChangeSetDetail } from '../../../../../shared/turnChangeSet';
+import { useLastTurnFilter } from './useLastTurnFilter';
+import {
+ useReviewBranchDiff,
+ useReviewCommitDiff,
+ useReviewFileDiffs,
+ useReviewGitState,
+} from './useReviewGitState';
+
+export const REVIEW_TURN_LOCAL_ONLY_ERROR = 'REVIEW_TURN_LOCAL_ONLY';
+
+export interface ReviewSourceData {
+ diffs: FileDiff[];
+ capped: ReviewCappedDiffData | null;
+ loading: boolean;
+ error: string | null;
+ refresh: () => void;
+ isPartial: boolean;
+ rawDiffCount: number;
+ lastTurnCount: number;
+ reviewData: ReviewData | null;
+ commitData: ReviewCommitDiffData | null;
+ branchData: ReviewBranchDiffData | null;
+ gitLoading: boolean;
+ gitError: string | null;
+ gitErrorCode: string | null;
+ refreshGit: () => void;
+ setReviewData: (data: ReviewData) => void;
+}
+
+interface TurnLoadState {
+ key: string | null;
+ changeSets: TurnChangeSetDetail[];
+ loading: boolean;
+ error: string | null;
+}
+
+function shouldHideWhitespaceOnlyDiff(diff: FileDiff, hideWhitespace: boolean): boolean {
+ return (
+ hideWhitespace && diff.kind === 'text' && diff.status === 'modified' && diff.hunks.length === 0
+ );
+}
+
+function filterWhitespaceHiddenDiffs(
+ diffs: readonly FileDiff[],
+ hideWhitespace: boolean,
+): FileDiff[] {
+ if (!hideWhitespace) return Array.from(diffs);
+ return diffs.filter((diff) => !shouldHideWhitespaceOnlyDiff(diff, true));
+}
+
+function fileDiffToSummaryEntry(diff: FileDiff): ReviewDiffSummaryEntry {
+ return {
+ id: diff.id,
+ source: diff.source,
+ path: diff.path,
+ oldPath: diff.oldPath,
+ status: diff.status,
+ additions: diff.additions,
+ deletions: diff.deletions,
+ changedLines: diff.additions + diff.deletions,
+ changedBytes: Math.max(0, diff.size ?? 0),
+ isBinary: diff.isBinary,
+ isSubmodule: diff.isSubmodule,
+ };
+}
+
+function getCurrentBranchDiffData(
+ data: ReviewBranchDiffData | null,
+ requestedBaseRef: string | null,
+): ReviewBranchDiffData | null {
+ if (!data) return null;
+ if (requestedBaseRef && data.baseRef !== requestedBaseRef) {
+ const isRequestedBaseFallback =
+ data.warning?.code === 'base-missing' && data.warning.requestedBaseRef === requestedBaseRef;
+ if (!isRequestedBaseFallback) return null;
+ }
+ return data;
+}
+
+export function useReviewSource(
+ descriptor: ReviewSourceDescriptor,
+ sessionId: string | null,
+ opts: {
+ hideWhitespace: boolean;
+ deviceLinkDeviceId: string | null;
+ remoteHostId: string | null;
+ },
+): ReviewSourceData {
+ const { hideWhitespace, deviceLinkDeviceId, remoteHostId } = opts;
+ const gitSessionId = descriptor.kind === 'turn-set' ? null : sessionId;
+ const branchBaseRef = descriptor.kind === 'branch' ? descriptor.baseRef : null;
+ const commitOid = descriptor.kind === 'commit' ? descriptor.commitOid : null;
+ const gitState = useReviewGitState(gitSessionId, hideWhitespace, deviceLinkDeviceId);
+ const commitState = useReviewCommitDiff(
+ gitSessionId,
+ commitOid,
+ hideWhitespace,
+ deviceLinkDeviceId,
+ );
+ const branchState = useReviewBranchDiff(
+ gitSessionId,
+ branchBaseRef,
+ hideWhitespace,
+ descriptor.kind === 'branch',
+ deviceLinkDeviceId,
+ );
+ const currentBranchData = getCurrentBranchDiffData(branchState.data, branchBaseRef);
+ const lastTurnPaths = useLastTurnFilter(gitSessionId, gitState.data?.scope.repoRoot ?? null);
+ const rawUnstaged = gitState.data?.diffs.unstaged ?? [];
+ const rawStaged = gitState.data?.diffs.staged ?? [];
+ const worktreeCapped = gitState.data?.diffs.capped ?? null;
+ const unstaged = useMemo(
+ () => filterWhitespaceHiddenDiffs(rawUnstaged, hideWhitespace),
+ [hideWhitespace, rawUnstaged],
+ );
+ const staged = useMemo(
+ () => filterWhitespaceHiddenDiffs(rawStaged, hideWhitespace),
+ [hideWhitespace, rawStaged],
+ );
+ const selectedCommitData = commitState.data?.commitOid === commitOid ? commitState.data : null;
+ const commitDiffs = useMemo(
+ () => filterWhitespaceHiddenDiffs(selectedCommitData?.diffs ?? [], hideWhitespace),
+ [hideWhitespace, selectedCommitData?.diffs],
+ );
+ const branchDiffs = useMemo(
+ () => filterWhitespaceHiddenDiffs(currentBranchData?.diffs ?? [], hideWhitespace),
+ [currentBranchData?.diffs, hideWhitespace],
+ );
+ const availableLastTurnDiffs = useMemo(
+ () =>
+ rawUnstaged
+ .concat(rawStaged)
+ .filter(
+ (diff) =>
+ lastTurnPaths.has(diff.path) ||
+ (diff.oldPath !== null && lastTurnPaths.has(diff.oldPath)),
+ ),
+ [lastTurnPaths, rawStaged, rawUnstaged],
+ );
+ const lastTurnCappedEntries = useMemo(
+ () =>
+ [...(worktreeCapped?.unstaged?.files ?? []), ...(worktreeCapped?.staged?.files ?? [])].filter(
+ (entry) =>
+ lastTurnPaths.has(entry.path) ||
+ (entry.oldPath !== null && lastTurnPaths.has(entry.oldPath)),
+ ),
+ [lastTurnPaths, worktreeCapped],
+ );
+ const lastTurnCapped = useMemo(
+ () =>
+ buildCappedDiffData([
+ ...availableLastTurnDiffs.map(fileDiffToSummaryEntry),
+ ...lastTurnCappedEntries,
+ ]),
+ [availableLastTurnDiffs, lastTurnCappedEntries],
+ );
+ const lastTurnHydrationRequests = useMemo<ReviewFileDiffRequest[]>(() => {
+ if (descriptor.kind !== 'last-turn' || lastTurnCapped || lastTurnCappedEntries.length === 0)
+ return [];
+ return lastTurnCappedEntries.map((entry) => ({
+ source: entry.source,
+ path: entry.path,
+ oldPath: entry.oldPath,
+ commitOid: null,
+ branchBaseRef: null,
+ ignoreWhitespace: hideWhitespace,
+ }));
+ }, [descriptor.kind, hideWhitespace, lastTurnCapped, lastTurnCappedEntries]);
+ const lastTurnHydratedState = useReviewFileDiffs(
+ gitSessionId,
+ lastTurnHydrationRequests,
+ deviceLinkDeviceId,
+ );
+ const hydratedLastTurnDiffs = useMemo(
+ () =>
+ lastTurnHydratedState.data
+ ?.map((item) => item.diff)
+ .filter((diff): diff is FileDiff => diff !== null) ?? [],
+ [lastTurnHydratedState.data],
+ );
+ const rawLastTurnDiffs = useMemo(
+ () => availableLastTurnDiffs.concat(hydratedLastTurnDiffs),
+ [availableLastTurnDiffs, hydratedLastTurnDiffs],
+ );
+ const lastTurnDiffs = useMemo(
+ () => filterWhitespaceHiddenDiffs(rawLastTurnDiffs, hideWhitespace),
+ [hideWhitespace, rawLastTurnDiffs],
+ );
+
+ const turnTargetSessionId = descriptor.kind === 'turn-set' ? descriptor.targetSessionId : null;
+ const turnChangeSetIdsKey =
+ descriptor.kind === 'turn-set' ? descriptor.changeSetIds.join('\0') : '';
+ const turnKey =
+ descriptor.kind === 'turn-set'
+ ? `${turnTargetSessionId ?? sessionId ?? ''}\0${turnChangeSetIdsKey}`
+ : null;
+ const [turnReloadToken, setTurnReloadToken] = useState(0);
+ const [turnState, setTurnState] = useState<TurnLoadState>({
+ key: null,
+ changeSets: [],
+ loading: false,
+ error: null,
+ });
+ useEffect(() => {
+ if (descriptor.kind !== 'turn-set' || !turnKey) return;
+ let cancelled = false;
+ if (!sessionId || remoteHostId !== null || deviceLinkDeviceId !== null) {
+ setTurnState({
+ key: turnKey,
+ changeSets: [],
+ loading: false,
+ error: REVIEW_TURN_LOCAL_ONLY_ERROR,
+ });
+ return;
+ }
+ setTurnState((current) => ({
+ key: turnKey,
+ changeSets: current.key === turnKey ? current.changeSets : [],
+ loading: true,
+ error: null,
+ }));
+ const reviewSessionId = turnTargetSessionId ?? sessionId;
+ void window.electronAPI.maker
+ .getTurnChangeSets(reviewSessionId, turnChangeSetIdsKey.split('\0'))
+ .then((changeSets) => {
+ if (!cancelled) setTurnState({ key: turnKey, changeSets, loading: false, error: null });
+ })
+ .catch((reason: unknown) => {
+ if (cancelled) return;
+ setTurnState({
+ key: turnKey,
+ changeSets: [],
+ loading: false,
+ error:
+ extractIpcError(reason)?.message ??
+ (reason instanceof Error ? reason.message : String(reason)),
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ descriptor.kind,
+ deviceLinkDeviceId,
+ remoteHostId,
+ sessionId,
+ turnChangeSetIdsKey,
+ turnKey,
+ turnReloadToken,
+ turnTargetSessionId,
+ ]);
+
+ const refreshTurn = useCallback(() => setTurnReloadToken((value) => value + 1), []);
+ const refreshGitSource = useCallback(() => {
+ gitState.refresh();
+ if (descriptor.kind === 'commit') commitState.refresh();
+ if (descriptor.kind === 'branch') branchState.refresh();
+ if (descriptor.kind === 'last-turn') lastTurnHydratedState.refresh();
+ }, [branchState, commitState, descriptor.kind, gitState, lastTurnHydratedState]);
+
+ if (descriptor.kind === 'turn-set') {
+ const currentTurnState =
+ turnState.key === turnKey
+ ? turnState
+ : { key: turnKey, changeSets: [], loading: true, error: null };
+ const rawDiffs = currentTurnState.changeSets.flatMap((changeSet) => changeSet.diffs);
+ return {
+ diffs: filterWhitespaceHiddenDiffs(rawDiffs, hideWhitespace),
+ capped: null,
+ loading: currentTurnState.loading,
+ error: currentTurnState.error,
+ refresh: refreshTurn,
+ isPartial: currentTurnState.changeSets.some((changeSet) => changeSet.state === 'partial'),
+ rawDiffCount: rawDiffs.length,
+ lastTurnCount: 0,
+ reviewData: null,
+ commitData: null,
+ branchData: null,
+ gitLoading: false,
+ gitError: null,
+ gitErrorCode: null,
+ refreshGit: gitState.refresh,
+ setReviewData: gitState.setData,
+ };
+ }
+
+ const sourceDiffs =
+ descriptor.kind === 'commit'
+ ? commitDiffs
+ : descriptor.kind === 'branch'
+ ? branchDiffs
+ : descriptor.kind === 'staged'
+ ? staged
+ : descriptor.kind === 'last-turn'
+ ? lastTurnDiffs
+ : unstaged;
+ const capped =
+ descriptor.kind === 'commit'
+ ? (selectedCommitData?.capped ?? null)
+ : descriptor.kind === 'branch'
+ ? (currentBranchData?.capped ?? null)
+ : descriptor.kind === 'staged'
+ ? (worktreeCapped?.staged ?? null)
+ : descriptor.kind === 'last-turn'
+ ? lastTurnCapped
+ : (worktreeCapped?.unstaged ?? null);
+ const loading =
+ descriptor.kind === 'commit'
+ ? commitState.loading
+ : descriptor.kind === 'branch'
+ ? branchState.loading
+ : descriptor.kind === 'last-turn'
+ ? lastTurnHydratedState.loading
+ : gitState.loading;
+ const error =
+ descriptor.kind === 'commit'
+ ? commitState.error
+ : descriptor.kind === 'branch'
+ ? branchState.error
+ : descriptor.kind === 'last-turn'
+ ? lastTurnHydratedState.error
+ : gitState.error;
+ const rawDiffCount =
+ descriptor.kind === 'commit'
+ ? (selectedCommitData?.diffs.length ?? 0)
+ : descriptor.kind === 'branch'
+ ? (currentBranchData?.diffs.length ?? 0)
+ : descriptor.kind === 'staged'
+ ? rawStaged.length
+ : descriptor.kind === 'last-turn'
+ ? rawLastTurnDiffs.length
+ : rawUnstaged.length;
+
+ return {
+ diffs: sourceDiffs,
+ capped,
+ loading,
+ error,
+ refresh: refreshGitSource,
+ isPartial: false,
+ rawDiffCount,
+ lastTurnCount:
+ lastTurnCapped?.stats.fileCount ??
+ availableLastTurnDiffs.length + lastTurnCappedEntries.length,
+ reviewData: gitState.data,
+ commitData: selectedCommitData,
+ branchData: currentBranchData,
+ gitLoading: gitState.loading,
+ gitError: gitState.error,
+ gitErrorCode: gitState.errorCode,
+ refreshGit: gitState.refresh,
+ setReviewData: gitState.setData,
+ };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c0ffc79942..064208f10a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4779,7 +4779,10 @@
"localOnly": "Exact message changes are not available for remote sessions yet.",
"partialNotice": "This message includes command or tool writes that could not be tracked exactly. Only the captured subset is shown; it is not a complete patch.",
"emptyTitle": "No recorded changes",
- "emptyDesc": "The recorded patch for this message has no displayable file changes."
+ "emptyDesc": "The recorded patch for this message has no displayable file changes.",
+ "crossSessionSwitchDisabled": "This review belongs to a collaborator session. Source switching is available only within its own session.",
+ "previewUnavailable": "This message records historical changes, so current on-disk file content cannot be previewed reliably.",
+ "snapshotPatchUnavailable": "A historical change snapshot cannot produce a git apply command for the current worktree."
},
"fileCount_one": "{{count}} file",
"fileCount_other": "{{count}} files",
@@ -4837,6 +4840,7 @@
"in-progress": "git operation in progress",
"agent-running": "agent is running",
"disabled": "review unavailable",
+ "historical-snapshot": "historical change snapshot is read-only",
"remote-device": "remote device sessions are view-only",
"remote-ssh": "SSH workspace review is view-only"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4006ef96bf..324ce22996 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4777,7 +4777,10 @@
"localOnly": "メッセージ単位の正確な変更は、リモートタスクではまだ利用できません。",
"partialNotice": "このメッセージには正確に追跡できないコマンドまたはツールの書き込みが含まれます。以下は取得できた一部のみで、完全なパッチではありません。",
"emptyTitle": "記録された変更はありません",
- "emptyDesc": "このメッセージで保存されたパッチに表示可能なファイル変更はありません。"
+ "emptyDesc": "このメッセージで保存されたパッチに表示可能なファイル変更はありません。",
+ "crossSessionSwitchDisabled": "このレビューはコラボレーターのセッションに属しています。ソースを切り替えられるのは、そのセッション内だけです。",
+ "previewUnavailable": "このメッセージは過去の変更を記録しているため、現在のディスク上のファイル内容を確実にプレビューできません。",
+ "snapshotPatchUnavailable": "過去の変更スナップショットから、現在の worktree 向けの git apply コマンドは生成できません。"
},
"fileCount_one": "{{count}} ファイル",
"fileCount_other": "{{count}} ファイル",
@@ -4835,6 +4838,7 @@
"in-progress": "git 操作が進行中です",
"agent-running": "エージェントが実行中です",
"disabled": "レビューを利用できません",
+ "historical-snapshot": "過去の変更スナップショットは読み取り専用です",
"remote-device": "リモートデバイスのセッションは閲覧のみです",
"remote-ssh": "SSH ワークスペースのレビューは表示専用です"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ab41fb9d8e..f04accdf0f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4777,7 +4777,10 @@
"localOnly": "메시지별 정확한 변경 사항은 아직 원격 작업에서 사용할 수 없습니다.",
"partialNotice": "이 메시지에는 정확히 추적할 수 없는 명령 또는 도구 쓰기가 포함되어 있습니다. 아래에는 캡처된 일부만 표시되며 완전한 패치가 아닙니다.",
"emptyTitle": "기록된 변경 사항 없음",
- "emptyDesc": "이 메시지에 저장된 패치에는 표시할 수 있는 파일 변경 사항이 없습니다."
+ "emptyDesc": "이 메시지에 저장된 패치에는 표시할 수 있는 파일 변경 사항이 없습니다.",
+ "crossSessionSwitchDisabled": "이 리뷰는 협업 세션에 속합니다. 소스 전환은 해당 세션 안에서만 사용할 수 있습니다.",
+ "previewUnavailable": "이 메시지는 과거 변경 사항을 기록하므로 현재 디스크의 파일 내용을 안정적으로 미리 볼 수 없습니다.",
+ "snapshotPatchUnavailable": "과거 변경 스냅샷에서는 현재 worktree용 git apply 명령을 만들 수 없습니다."
},
"fileCount_one": "{{count}}개 파일",
"fileCount_other": "{{count}}개 파일",
@@ -4835,6 +4838,7 @@
"in-progress": "git 작업 진행 중",
"agent-running": "에이전트 실행 중",
"disabled": "리뷰를 사용할 수 없음",
+ "historical-snapshot": "과거 변경 스냅샷은 읽기 전용입니다",
"remote-device": "원격 기기 세션은 보기 전용입니다",
"remote-ssh": "SSH 워크스페이스 검토는 보기 전용입니다"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e91472b54f..b83d0d582c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4773,7 +4773,10 @@
"localOnly": "本条消息的精确变更暂不支持远程任务。",
"partialNotice": "本条消息包含无法精确追踪的命令或工具写入;以下仅展示已精确捕获的部分,不能视为完整补丁。",
"emptyTitle": "没有已记录的变更",
- "emptyDesc": "这条消息记录的补丁中没有可显示的文件变更。"
+ "emptyDesc": "这条消息记录的补丁中没有可显示的文件变更。",
+ "crossSessionSwitchDisabled": "正在审查协作任务中的这条消息,不能在当前任务中切换来源。",
+ "previewUnavailable": "这条消息记录的是历史变更,无法可靠预览当前磁盘中的文件内容。",
+ "snapshotPatchUnavailable": "历史变更快照不能生成面向当前 worktree 的 git apply 命令。"
},
"fileCount_one": "{{count}} 个文件",
"fileCount_other": "{{count}} 个文件",
@@ -4831,6 +4834,7 @@
"in-progress": "git 操作进行中",
"agent-running": "Agent 正在运行",
"disabled": "审查不可用",
+ "historical-snapshot": "历史变更快照为只读",
"remote-device": "远程设备任务仅支持查看",
"remote-ssh": "SSH 工作区审查仅支持查看"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index b46ec0dfe9..d2404e67b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4776,7 +4776,10 @@
"localOnly": "本條訊息的精確變更暫不支援遠端任務。",
"partialNotice": "本條訊息包含無法精確追蹤的命令或工具寫入;以下僅展示已精確捕獲的部分,不能視為完整補丁。",
"emptyTitle": "沒有已記錄的變更",
- "emptyDesc": "這條訊息記錄的補丁中沒有可顯示的檔案變更。"
+ "emptyDesc": "這條訊息記錄的補丁中沒有可顯示的檔案變更。",
+ "crossSessionSwitchDisabled": "正在審查協作任務中的這條訊息,不能在目前任務中切換來源。",
+ "previewUnavailable": "這條訊息記錄的是歷史變更,無法可靠預覽目前磁碟中的檔案內容。",
+ "snapshotPatchUnavailable": "歷史變更快照不能產生面向目前 worktree 的 git apply 指令。"
},
"fileCount_one": "{{count}} 個檔案",
"fileCount_other": "{{count}} 個檔案",
@@ -4834,6 +4837,7 @@
"in-progress": "git 操作進行中",
"agent-running": "Agent 正在執行",
"disabled": "審查不可用",
+ "historical-snapshot": "歷史變更快照為唯讀",
"remote-device": "遠端設備任務僅支援檢視",
"remote-ssh": "SSH 工作區審查僅支援檢視"
},
diff --git a/apps/desktop/src/shared/__tests__/reviewSource.test.ts b/apps/desktop/src/shared/__tests__/reviewSource.test.ts
new file mode 100644
index 0000000000..89ee87814b
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/reviewSource.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ capabilitiesFor,
+ migrateLegacyTurnTarget,
+ parseReviewJumpTarget,
+ parseReviewSourceDescriptor,
+ type ReviewSourceDescriptor,
+} from '../reviewSource';
+
+describe('review source descriptor', () => {
+ it.each<ReviewSourceDescriptor>([
+ { kind: 'unstaged' },
+ { kind: 'staged' },
+ { kind: 'commit', commitOid: 'a'.repeat(40) },
+ { kind: 'branch', baseRef: 'origin/main' },
+ { kind: 'last-turn' },
+ { kind: 'turn-set', targetSessionId: 'worker', changeSetIds: ['set-1'] },
+ ])('round-trips a valid $kind descriptor', (descriptor) => {
+ expect(parseReviewSourceDescriptor(descriptor)).toEqual(descriptor);
+ });
+
+ it('rejects unsafe or incomplete persisted descriptors', () => {
+ expect(parseReviewSourceDescriptor({ kind: 'branch', baseRef: '-unsafe' })).toBeNull();
+ expect(parseReviewSourceDescriptor({ kind: 'commit', commitOid: '' })).toBeNull();
+ expect(
+ parseReviewSourceDescriptor({
+ kind: 'turn-set',
+ targetSessionId: 'worker',
+ changeSetIds: [],
+ }),
+ ).toBeNull();
+ expect(parseReviewSourceDescriptor({ kind: 'unknown' })).toBeNull();
+ });
+
+ it('parses finite jump targets and rejects malformed persisted values', () => {
+ expect(parseReviewJumpTarget({ diffId: null, path: 'src/a.ts', nonce: 4 })).toEqual({
+ diffId: null,
+ path: 'src/a.ts',
+ nonce: 4,
+ });
+ expect(
+ parseReviewJumpTarget({ diffId: 'unstaged: spaced ', path: ' spaced ', nonce: 5 }),
+ ).toEqual({
+ diffId: 'unstaged: spaced ',
+ path: ' spaced ',
+ nonce: 5,
+ });
+ expect(parseReviewJumpTarget({ diffId: null, path: null, nonce: Number.NaN })).toBeNull();
+ expect(parseReviewJumpTarget({ diffId: null, path: null, nonce: 1.5 })).toBeNull();
+ expect(parseReviewJumpTarget({ diffId: 42, path: null, nonce: 1 })).toBeNull();
+ });
+
+ it('migrates legacy turn state without retaining malformed ids', () => {
+ expect(
+ migrateLegacyTurnTarget({
+ changeSetIds: ['set-1'],
+ selectedDiffId: 'unstaged:src/a.ts',
+ selectedPath: 'src/a.ts',
+ requestNonce: 7,
+ targetSessionId: 'worker',
+ }),
+ ).toEqual({
+ descriptor: { kind: 'turn-set', targetSessionId: 'worker', changeSetIds: ['set-1'] },
+ jumpTarget: { diffId: 'unstaged:src/a.ts', path: 'src/a.ts', nonce: 7 },
+ });
+ expect(
+ migrateLegacyTurnTarget({
+ changeSetIds: Array.from({ length: 17 }, (_, index) => String(index)),
+ }),
+ ).toBeNull();
+ expect(
+ parseReviewSourceDescriptor({
+ kind: 'turn-set',
+ targetSessionId: 'worker',
+ changeSetIds: ['x'.repeat(257)],
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('review source capabilities', () => {
+ it('keeps live git sources interactive while historical snapshots are read-only', () => {
+ expect(capabilitiesFor({ kind: 'unstaged' })).toMatchObject({
+ canDiscardHunk: true,
+ canCommit: true,
+ canPush: true,
+ canRichPreview: true,
+ canOpenFile: true,
+ canSwitchSource: true,
+ showBranchInfo: true,
+ });
+ expect(capabilitiesFor({ kind: 'last-turn' })).toMatchObject({
+ canDiscardHunk: false,
+ canCommit: true,
+ canPush: true,
+ canRichPreview: true,
+ canOpenFile: true,
+ });
+ expect(
+ capabilitiesFor({ kind: 'turn-set', targetSessionId: null, changeSetIds: ['set-1'] }),
+ ).toEqual({
+ canDiscardHunk: false,
+ canCommit: false,
+ canPush: false,
+ canRichPreview: false,
+ canOpenFile: false,
+ canSwitchSource: true,
+ showBranchInfo: false,
+ });
+ });
+});
diff --git a/apps/desktop/src/shared/reviewSource.ts b/apps/desktop/src/shared/reviewSource.ts
new file mode 100644
index 0000000000..dff846646e
--- /dev/null
+++ b/apps/desktop/src/shared/reviewSource.ts
@@ -0,0 +1,153 @@
+import { isSafeBranchBaseRef } from './reviewBranchRef';
+
+export type ReviewSourceDescriptor =
+ | { kind: 'unstaged' }
+ | { kind: 'staged' }
+ | { kind: 'commit'; commitOid: string | null }
+ | { kind: 'branch'; baseRef: string | null }
+ | { kind: 'last-turn' }
+ | { kind: 'turn-set'; targetSessionId: string | null; changeSetIds: string[] };
+
+/** Entry-point positioning is independent from the selected review data source. */
+export interface ReviewJumpTarget {
+ diffId: string | null;
+ path: string | null;
+ nonce: number;
+}
+
+export interface ReviewCapabilities {
+ canDiscardHunk: boolean;
+ canCommit: boolean;
+ canPush: boolean;
+ canRichPreview: boolean;
+ canOpenFile: boolean;
+ canSwitchSource: boolean;
+ showBranchInfo: boolean;
+}
+
+export interface MigratedLegacyTurnTarget {
+ descriptor: Extract<ReviewSourceDescriptor, { kind: 'turn-set' }>;
+ jumpTarget: ReviewJumpTarget;
+}
+
+const MAX_CHANGE_SET_IDS = 16;
+const MAX_ID_LENGTH = 256;
+const MAX_DIFF_ID_LENGTH = 512;
+
+function nullableString(
+ value: unknown,
+ maxLength = Number.POSITIVE_INFINITY,
+): string | null | undefined {
+ if (value === null || value === undefined) return null;
+ if (typeof value !== 'string') return undefined;
+ const trimmed = value.trim();
+ return trimmed === '' || trimmed.length > maxLength ? undefined : trimmed;
+}
+
+function nullableOpaqueString(
+ value: unknown,
+ maxLength = Number.POSITIVE_INFINITY,
+): string | null | undefined {
+ if (value === null || value === undefined) return null;
+ if (typeof value !== 'string') return undefined;
+ return value === '' || value.length > maxLength ? undefined : value;
+}
+
+function parseChangeSetIds(value: unknown): string[] | null {
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CHANGE_SET_IDS) return null;
+ if (
+ !value.every(
+ (id) => typeof id === 'string' && id.trim() !== '' && id.trim().length <= MAX_ID_LENGTH,
+ )
+ )
+ return null;
+ return value.map((id) => id.trim());
+}
+
+export function parseReviewSourceDescriptor(value: unknown): ReviewSourceDescriptor | null {
+ if (!value || typeof value !== 'object') return null;
+ const obj = value as Record<string, unknown>;
+ if (obj.kind === 'unstaged' || obj.kind === 'staged' || obj.kind === 'last-turn') {
+ return { kind: obj.kind };
+ }
+ if (obj.kind === 'commit') {
+ const commitOid = nullableString(obj.commitOid, MAX_ID_LENGTH);
+ return commitOid === undefined ? null : { kind: 'commit', commitOid };
+ }
+ if (obj.kind === 'branch') {
+ const baseRef = nullableString(obj.baseRef);
+ if (baseRef === undefined || (baseRef !== null && !isSafeBranchBaseRef(baseRef))) return null;
+ return { kind: 'branch', baseRef };
+ }
+ if (obj.kind === 'turn-set') {
+ const changeSetIds = parseChangeSetIds(obj.changeSetIds);
+ const targetSessionId = nullableString(obj.targetSessionId, MAX_ID_LENGTH);
+ if (!changeSetIds || targetSessionId === undefined) return null;
+ return { kind: 'turn-set', targetSessionId, changeSetIds };
+ }
+ return null;
+}
+
+export function parseReviewJumpTarget(value: unknown): ReviewJumpTarget | null {
+ if (!value || typeof value !== 'object') return null;
+ const obj = value as Record<string, unknown>;
+ const diffId = nullableOpaqueString(obj.diffId, MAX_DIFF_ID_LENGTH);
+ const path = nullableOpaqueString(obj.path);
+ const nonce = obj.nonce;
+ if (
+ diffId === undefined ||
+ path === undefined ||
+ typeof nonce !== 'number' ||
+ !Number.isSafeInteger(nonce) ||
+ nonce < 0
+ ) {
+ return null;
+ }
+ return { diffId, path, nonce };
+}
+
+/** Maps persisted pre-descriptor state without mutating the stored legacy payload. */
+export function migrateLegacyTurnTarget(value: unknown): MigratedLegacyTurnTarget | null {
+ if (!value || typeof value !== 'object') return null;
+ const obj = value as Record<string, unknown>;
+ const changeSetIds = parseChangeSetIds(obj.changeSetIds);
+ const targetSessionId = nullableString(obj.targetSessionId, MAX_ID_LENGTH);
+ const diffId = nullableOpaqueString(obj.selectedDiffId, MAX_DIFF_ID_LENGTH);
+ const path = nullableOpaqueString(obj.selectedPath);
+ const nonce =
+ typeof obj.requestNonce === 'number' &&
+ Number.isSafeInteger(obj.requestNonce) &&
+ obj.requestNonce >= 0
+ ? obj.requestNonce
+ : 0;
+ if (!changeSetIds || targetSessionId === undefined || diffId === undefined || path === undefined)
+ return null;
+ return {
+ descriptor: { kind: 'turn-set', targetSessionId, changeSetIds },
+ jumpTarget: { diffId, path, nonce },
+ };
+}
+
+export function capabilitiesFor(descriptor: ReviewSourceDescriptor): ReviewCapabilities {
+ if (descriptor.kind === 'turn-set') {
+ return {
+ canDiscardHunk: false,
+ canCommit: false,
+ canPush: false,
+ canRichPreview: false,
+ canOpenFile: false,
+ canSwitchSource: true,
+ showBranchInfo: false,
+ };
+ }
+
+ return {
+ canDiscardHunk: descriptor.kind === 'unstaged',
+ canCommit: true,
+ canPush: true,
+ canRichPreview: true,
+ canOpenFile: true,
+ canSwitchSource: true,
+ showBranchInfo: true,
+ };
+}