🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
'use client';
import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';
import { ActionIcon, Center, type DropdownItem, DropdownMenu, Empty, Flexbox } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import {
ArrowLeftIcon,
ChevronDownIcon,
Columns2Icon,
FoldVerticalIcon,
GitCompareIcon,
MoreHorizontalIcon,
PanelRightCloseIcon,
PanelRightOpenIcon,
RefreshCwIcon,
RotateCcwIcon,
Rows2Icon,
UnfoldVerticalIcon,
WholeWordIcon,
WrapTextIcon,
} from 'lucide-react';
import path from 'path-browserify-esm';
import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SkeletonList } from '@/components/Skeleton/NavPanel/List';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
import { useFetchGitBranch } from '@/store/device';
import { sidebarRow } from '@/styles/density.stylex';
import { sx } from '@/styles/sx';
import type { ComposerTarget } from '../../types';
import FileRow from './FileRow';
import FileTreeNav from './FileTreeNav';
import GroupHeader from './GroupHeader';
import { getDefaultExpandedKeys, itemKey } from './reviewTreeNodes';
import {
getReviewSummaryState,
invalidateGitReviewCaches,
type ReviewMode,
useGitRemoteBranches,
useReviewPatches,
} from './useReviewPatches';
interface RepoGroup {
absolutePath: string;
branch?: string;
detached?: boolean;
isParent: boolean;
name: string;
patches: GitWorkingTreePatch[];
}
const WORD_WRAP_STORAGE_KEY = 'lobechat-review-word-wrap';
const TEXT_DIFF_STORAGE_KEY = 'lobechat-review-text-diff';
const VIEW_MODE_STORAGE_KEY = 'lobechat-review-view-mode';
const REVIEW_MODE_STORAGE_KEY = 'lobechat-review-mode';
const BASE_REF_OVERRIDES_STORAGE_KEY = 'lobechat-review-base-overrides';
interface ReviewProps {
active: boolean;
composerTarget: ComposerTarget;
/**
* Target device the working directory lives on. Undefined for local desktop;
* set for a remote / web-bound device so git ops route through the device RPCs.
*/
deviceId?: string;
/** Toggle the tree-nav rail. Owned by the sidebar so it can widen the panel. */
onToggleTree: () => void;
/** Whether the right-hand tree-nav rail is shown (two-pane). */
showTree: boolean;
workingDirectory: string;
}
const styles = stylex.create({
caret: { flexShrink: 0, color: cssVar.colorTextTertiary },
totalAdditions: { color: cssVar.colorSuccess },
totalDeletions: { color: cssVar.colorError },
totalStats: {
display: 'inline-flex',
flexShrink: 0,
gap: '6px',
alignItems: 'center',
fontFamily: cssVar.fontFamilyCode,
fontSize: '12px',
fontVariantNumeric: 'tabular-nums',
},
// Two-pane body: diff list (left, flexes) + tree-nav rail (right, fixed).
body: { overflow: 'hidden', minHeight: 0 },
// The first row drops its own top border (see FileRow): the list's
// border-block-start already separates it from the subheader.
list: {
position: 'relative',
minWidth: 0,
borderBlockWidth: '1px',
borderBlockStyle: 'solid',
borderBlockColor: cssVar.colorBorderSecondary,
},
treeRail: {
flex: 'none',
width: '240px',
minHeight: 0,
paddingBlock: '4px',
borderBlockStartWidth: '1px',
borderBlockStartStyle: 'solid',
borderBlockStartColor: cssVar.colorBorderSecondary,
borderInlineStartWidth: '1px',
borderInlineStartStyle: 'solid',
borderInlineStartColor: cssVar.colorBorderSecondary,
},
arrow: { flexShrink: 0, color: cssVar.colorTextTertiary },
basePicker: {
cursor: 'pointer',
userSelect: 'none',
overflow: 'hidden',
display: 'inline-flex',
flexGrow: '0',
flexShrink: '1',
flexBasis: 'auto',
gap: '4px',
alignItems: 'center',
minWidth: 0,
paddingBlock: '1px',
paddingInline: '6px',
borderRadius: '4px',
transition: 'background 0.15s',
backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
backgroundImage: { 'default': null, ':hover': 'none' },
},
compareChip: {
overflow: 'hidden',
display: 'inline-flex',
flexGrow: '0',
flexShrink: '1',
flexBasis: 'auto',
gap: '6px',
alignItems: 'center',
minWidth: 0,
},
headRefText: {
overflow: 'hidden',
flexGrow: '0',
flexShrink: '1',
flexBasis: 'auto',
minWidth: 0,
paddingInlineEnd: '4px',
fontFamily: cssVar.fontFamilyCode,
fontSize: '12px',
color: cssVar.colorTextSecondary,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
refName: {
overflow: 'hidden',
flexGrow: '0',
flexShrink: '1',
flexBasis: 'auto',
minWidth: 0,
fontFamily: cssVar.fontFamilyCode,
fontSize: '12px',
color: cssVar.colorText,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
scopeChip: {
cursor: 'pointer',
userSelect: 'none',
display: 'inline-flex',
flexShrink: 0,
gap: '6px',
alignItems: 'center',
paddingBlock: '2px',
paddingInline: '6px',
borderRadius: '4px',
fontSize: '12px',
color: cssVar.colorTextSecondary,
transition: 'background 0.15s',
backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
backgroundImage: { 'default': null, ':hover': 'none' },
},
subheader: {
display: 'flex',
flexShrink: 0,
gap: '4px',
alignItems: 'center',
justifyContent: 'space-between',
height: sidebarRow.toolbarHeight,
paddingInlineStart: sidebarRow.toolbarPaddingInlineStart,
paddingInlineEnd: sidebarRow.toolbarPaddingInlineEnd,
},
skeleton: {
paddingBlockStart: sidebarRow.paneBlockStart,
paddingBlockEnd: sidebarRow.paneBlockEnd,
paddingInline: sidebarRow.paneInline,
},
// Empty submodule group — pointer-only bump where the submodule's own
// working tree is clean. We still surface the group so the user knows the
// submodule pointer moved, just with a softer "no changes" line instead of
// a list of files.
groupEmpty: {
paddingBlockStart: '6px',
paddingBlockEnd: '10px',
paddingInline: sidebarRow.paddingInline,
borderBlockStartWidth: { 'default': '1px', ':first-child': 'medium' },
borderBlockStartStyle: { 'default': 'solid', ':first-child': 'none' },
borderBlockStartColor: {
'default': cssVar.colorBorderSecondary,
':first-child': 'currentcolor',
},
fontSize: '12px',
color: cssVar.colorTextTertiary,
},
});
const Review = memo<ReviewProps>(
({ active, composerTarget, deviceId, onToggleTree, showTree, workingDirectory }) => {
const { t } = useTranslation('chat');
const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');
// Per-repo base-ref override — when set, the branch diff compares against
// this ref instead of `origin/HEAD`. Stored as a single keyed object so we
// don't proliferate localStorage keys across repos.
const [baseOverrides, setBaseOverrides] = useLocalStorageState<Record<string, string>>(
BASE_REF_OVERRIDES_STORAGE_KEY,
{},
);
const baseOverride = baseOverrides[workingDirectory];
const setBaseOverride = (next: string | undefined) => {
setBaseOverrides((prev) => {
const updated = { ...prev };
if (next === undefined) delete updated[workingDirectory];
else updated[workingDirectory] = next;
return updated;
});
};
// Stale-first: after a reload the replica paints the last persisted summary
// (paths + counts, no diff text); expanded rows wait for the live diff.
const { data, error, isLoading, isValidating } = useReviewPatches(
workingDirectory,
mode,
baseOverride,
deviceId,
active,
);
const { diffPending, isSummary } = getReviewSummaryState(data, error);
const invalidateReviewData = useCallback(
async () =>
invalidateGitReviewCaches({
baseRef: baseOverride,
deviceId,
dirPath: workingDirectory,
mode,
}),
[baseOverride, deviceId, mode, workingDirectory],
);
useEffect(() => {
if (!active) return;
void invalidateReviewData();
}, [active, invalidateReviewData]);
// Lazy: only fetch remote branches list once the user opens the picker.
const [basePickerOpen, setBasePickerOpen] = useState(false);
const { data: remoteBranches } = useGitRemoteBranches(
workingDirectory,
mode === 'branch' && basePickerOpen,
deviceId,
);
// Memo-stabilise the fallback so downstream useMemo deps don't flap on
// every render while the SWR result is undefined.
const patches = useMemo(() => data?.patches ?? [], [data]);
const submoduleGroups = useMemo(() => data?.submodules ?? [], [data]);
const baseRef = data?.mode === 'branch' ? data.baseRef : undefined;
const headRef = data?.mode === 'branch' ? data.headRef : undefined;
// Parent branch — only needed for the group header label, so we only fetch
// it when there's at least one submodule group to render alongside it.
// SWR-deduped under the hood by `useFetchGitBranch`'s own cache key. Routes
// through the target device so remote repos resolve the same way.
const { data: parentGitInfo } = useFetchGitBranch(
deviceId,
submoduleGroups.length > 0 ? workingDirectory : undefined,
);
const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(
VIEW_MODE_STORAGE_KEY,
'unified',
);
const [wordWrap, setWordWrap] = useLocalStorageState<boolean>(WORD_WRAP_STORAGE_KEY, false);
// pierre/diffs default lineDiffType is 'word-alt' (text-level highlighting on),
// so we default the persisted toggle to true to preserve current behaviour.
const [textDiff, setTextDiff] = useLocalStorageState<boolean>(TEXT_DIFF_STORAGE_KEY, true);
// Build the per-repo group list. The parent always comes first; submodules
// follow in the order the IPC returned them (which is the order they appear
// in `git status`). The parent group is dropped when it has zero patches
// *and* at least one submodule exists — we don't want an empty parent
// header hovering above the submodule rows. Submodule groups with zero
// patches (pointer-only bumps) are intentionally kept so the user still
// sees the submodule surfaced.
const groups = useMemo<RepoGroup[]>(() => {
const result: RepoGroup[] = [];
if (patches.length > 0 || submoduleGroups.length === 0) {
result.push({
absolutePath: workingDirectory,
branch: parentGitInfo?.branch,
detached: parentGitInfo?.detached,
isParent: true,
name: path.basename(workingDirectory) || workingDirectory,
patches,
});
}
for (const sub of submoduleGroups) {
result.push({
absolutePath: sub.absolutePath,
branch: sub.branch,
detached: sub.detached,
isParent: false,
name: sub.name,
patches: sub.patches,
});
}
return result;
}, [
workingDirectory,
parentGitInfo?.branch,
parentGitInfo?.detached,
patches,
submoduleGroups,
]);
const showGroupHeaders = submoduleGroups.length > 0;
const allEntries = useMemo(
() => groups.flatMap((g) => g.patches.map((p) => ({ group: g, patch: p }))),
[groups],
);
// Per-group collapse state — ephemeral (not persisted across reloads).
// Stored as a set of repo absolutePaths; entries linger if a group later
// disappears, which is harmless since nothing renders for missing paths.
const [collapsedGroupPaths, setCollapsedGroupPaths] = useState<Set<string>>(() => new Set());
const toggleGroupCollapsed = (absolutePath: string) => {
setCollapsedGroupPaths((prev) => {
const next = new Set(prev);
if (next.has(absolutePath)) next.delete(absolutePath);
else next.add(absolutePath);
return next;
});
};
// A PatchDiff materialises a large Shiki-backed DOM tree. Keep the initial
// expansion to a viewport-sized batch; users can still open any other file.
const signature = useMemo(
() => allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)).join('|'),
[allEntries],
);
const [seenSignature, setSeenSignature] = useState('');
const [activeKeys, setActiveKeys] = useState<string[]>([]);
if (signature !== seenSignature) {
setSeenSignature(signature);
setActiveKeys(getDefaultExpandedKeys(groups));
}
// The file whose diff the tree-nav last scrolled to — highlighted in the rail.
const [activeFileKey, setActiveFileKey] = useState<string | undefined>();
// Scroll container for the left diff list; tree-nav clicks scroll it to the
// matching `[data-file-key]` row.
const listRef = useRef<HTMLDivElement>(null);
const toggleFileKey = (key: string) =>
setActiveKeys((prev) =>
prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],
);
// Tree-nav → diff list: reveal the group, expand the file, scroll it into view.
const handleSelectFile = (key: string) => {
setActiveFileKey(key);
const groupPath = key.slice(0, key.indexOf('|'));
setCollapsedGroupPaths((prev) => {
if (!prev.has(groupPath)) return prev;
const next = new Set(prev);
next.delete(groupPath);
return next;
});
setActiveKeys((prev) => (prev.includes(key) ? prev : [...prev, key]));
// Defer until the row is mounted/uncollapsed, then scroll it to the top.
requestAnimationFrame(() => {
const el = listRef.current?.querySelector(`[data-file-key="${CSS.escape(key)}"]`);
el?.scrollIntoView({ block: 'start' });
});
};
if (!data && isLoading) {
return <SkeletonList compact className={stylex.props(styles.skeleton).className} rows={6} />;
}
const totalEntryCount = allEntries.length;
const allExpanded = totalEntryCount > 0 && activeKeys.length === totalEntryCount;
const handleToggleAll = () => {
setActiveKeys(
allExpanded ? [] : allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)),
);
};
const totals = allEntries.reduce(
(acc, { patch }) => {
acc.additions += patch.additions ?? 0;
acc.deletions += patch.deletions ?? 0;
return acc;
},
{ additions: 0, deletions: 0 },
);
const moreMenuItems: DropdownItem[] = [
{
icon: <RefreshCwIcon size={14} />,
key: 'refresh',
label: t('workingPanel.review.refresh'),
onClick: () => void invalidateReviewData(),
},
{ type: 'divider' },
{
icon: <WrapTextIcon size={14} />,
key: 'wordWrap',
label: wordWrap
? t('workingPanel.review.wordWrap.disable')
: t('workingPanel.review.wordWrap.enable'),
onClick: () => setWordWrap((w) => !w),
},
{
icon: <WholeWordIcon size={14} />,
key: 'textDiff',
label: textDiff
? t('workingPanel.review.textDiff.disable')
: t('workingPanel.review.textDiff.enable'),
onClick: () => setTextDiff((v) => !v),
},
{
icon: viewMode === 'unified' ? <Columns2Icon size={14} /> : <Rows2Icon size={14} />,
key: 'viewMode',
label:
viewMode === 'unified'
? t('workingPanel.review.viewMode.split')
: t('workingPanel.review.viewMode.unified'),
onClick: () => setViewMode((m) => (m === 'unified' ? 'split' : 'unified')),
},
];
const modeMenuItems: DropdownItem[] = [
{
key: 'unstaged',
label: t('workingPanel.review.mode.unstaged'),
onClick: () => setMode('unstaged'),
},
{
key: 'branch',
label: t('workingPanel.review.mode.branch'),
onClick: () => setMode('branch'),
},
];
// Branches are only loaded after the user opens the picker (see
// `basePickerOpen`). While loading, render a single disabled placeholder
// so the menu doesn't pop empty + jump to its final size.
const baseRefMenuItems: DropdownItem[] = remoteBranches
? [
...remoteBranches.map((branch) => ({
key: branch.name,
label: branch.isDefault
? `${branch.name} · ${t('workingPanel.review.baseRef.default')}`
: branch.name,
onClick: () =>
setBaseOverride(branch.isDefault && !baseOverride ? undefined : branch.name),
})),
...(baseOverride
? [
{ type: 'divider' as const },
{
icon: <RotateCcwIcon size={14} />,
key: 'reset',
label: t('workingPanel.review.baseRef.reset'),
onClick: () => setBaseOverride(undefined),
},
]
: []),
]
: [
{
disabled: true,
key: 'loading',
label: t('workingPanel.review.baseRef.loading'),
},
];
// A pointer-only submodule bump produces a group with no file patches but is
// still worth surfacing (the GroupHeader + "submodule clean" line), so don't
// collapse into the global empty state when any submodule group is present.
const isEmpty = totalEntryCount === 0 && submoduleGroups.length === 0;
const emptyText =
mode === 'branch'
? baseRef
? t('workingPanel.review.empty.branch', { baseRef })
: t('workingPanel.review.empty.noBaseRef')
: t('workingPanel.review.empty');
return (
<Flexbox style={{ overflow: 'hidden' }} width={'100%'}>
<div {...stylex.props(styles.subheader)}>
<Flexbox
horizontal
align={'center'}
gap={8}
style={{ flex: '1 1 auto', minWidth: 0, overflow: 'hidden' }}
>
<DropdownMenu items={modeMenuItems} placement={'bottomLeft'}>
<span {...stylex.props(styles.scopeChip)} role={'button'} tabIndex={0}>
{mode === 'branch'
? t('workingPanel.review.mode.branch')
: t('workingPanel.review.mode.unstaged')}
<ChevronDownIcon {...stylex.props(styles.caret)} size={12} />
</span>
</DropdownMenu>
{mode === 'branch' && (baseRef || headRef) && (
<span {...stylex.props(styles.compareChip)}>
<DropdownMenu
items={baseRefMenuItems}
placement={'bottomLeft'}
onOpenChange={setBasePickerOpen}
>
<span {...stylex.props(styles.basePicker)} role={'button'} tabIndex={0}>
<span {...stylex.props(styles.refName)}>
{baseRef ?? t('workingPanel.review.baseRef.unresolved')}
</span>
<ChevronDownIcon {...stylex.props(styles.caret)} size={12} />
</span>
</DropdownMenu>
{headRef && (
<>
<ArrowLeftIcon {...stylex.props(styles.arrow)} size={12} />
<span {...stylex.props(styles.headRefText)}>{headRef}</span>
</>
)}
</span>
)}
{(totals.additions > 0 || totals.deletions > 0) && (
<span {...stylex.props(styles.totalStats)}>
{totals.additions > 0 && (
<span {...stylex.props(styles.totalAdditions)}>+{totals.additions}</span>
)}
{totals.deletions > 0 && (
<span {...stylex.props(styles.totalDeletions)}>-{totals.deletions}</span>
)}
</span>
)}
</Flexbox>
<Flexbox horizontal align={'center'} gap={2}>
{totalEntryCount > 0 && (
<ActionIcon
icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}
size={'small'}
title={
allExpanded
? t('workingPanel.review.collapseAll')
: t('workingPanel.review.expandAll')
}
onClick={handleToggleAll}
/>
)}
{totalEntryCount > 0 && (
<ActionIcon
active={showTree}
icon={showTree ? PanelRightCloseIcon : PanelRightOpenIcon}
size={'small'}
title={
showTree ? t('workingPanel.review.tree.hide') : t('workingPanel.review.tree.show')
}
onClick={onToggleTree}
/>
)}
<DropdownMenu items={moreMenuItems} placement={'bottomRight'}>
<ActionIcon
icon={MoreHorizontalIcon}
loading={isValidating}
size={'small'}
title={t('workingPanel.review.more')}
/>
</DropdownMenu>
</Flexbox>
</div>
{isEmpty ? (
<Center flex={1} paddingBlock={24}>
<Empty description={emptyText} icon={GitCompareIcon} />
</Center>
) : (
<Flexbox horizontal {...stylex.props(styles.body)} flex={1} width={'100%'}>
<Flexbox flex={1} ref={listRef} {...sx(styles.list, { overflow: 'auto' })}>
{groups.map((group) => {
const groupTotals = group.patches.reduce(
(acc, p) => {
acc.additions += p.additions ?? 0;
acc.deletions += p.deletions ?? 0;
return acc;
},
{ additions: 0, deletions: 0 },
);
const groupCollapsed = collapsedGroupPaths.has(group.absolutePath);
const groupItemKeys = group.patches.map((p) => itemKey(group.absolutePath, p));
const groupAllExpanded =
groupItemKeys.length > 0 && groupItemKeys.every((k) => activeKeys.includes(k));
const toggleGroupDiffs = () => {
setActiveKeys((prev) => {
if (groupAllExpanded) {
const set = new Set(groupItemKeys);
return prev.filter((k) => !set.has(k));
}
const next = new Set(prev);
for (const k of groupItemKeys) next.add(k);
return Array.from(next);
});
};
return (
<Fragment key={group.absolutePath}>
{showGroupHeaders && (
<GroupHeader
branch={group.branch}
collapsed={groupCollapsed}
diffsAllExpanded={groupAllExpanded}
hideFoldButton={groupCollapsed || group.patches.length === 0}
name={group.name}
patchCount={group.patches.length}
totalAdditions={groupTotals.additions}
totalDeletions={groupTotals.deletions}
onToggleCollapsed={() => toggleGroupCollapsed(group.absolutePath)}
onToggleDiffs={toggleGroupDiffs}
/>
)}
{showGroupHeaders &&
!groupCollapsed &&
!group.isParent &&
group.patches.length === 0 && (
<div {...stylex.props(styles.groupEmpty)}>
{t('workingPanel.review.group.submoduleClean')}
</div>
)}
{!groupCollapsed &&
group.patches.length > 0 &&
group.patches.map((entry) => {
const key = itemKey(group.absolutePath, entry);
const expanded = activeKeys.includes(key);
return (
<FileRow
composerTarget={composerTarget}
dataFileKey={key}
deviceId={deviceId}
entry={entry}
expanded={expanded}
key={key}
mode={mode}
pending={diffPending}
repoAbsolutePath={group.absolutePath}
stale={isSummary}
textDiff={textDiff}
viewMode={viewMode}
wordWrap={wordWrap}
onReverted={() => void invalidateReviewData()}
onToggle={() => toggleFileKey(key)}
/>
);
})}
</Fragment>
);
})}
</Flexbox>
{showTree && (
<Flexbox {...stylex.props(styles.treeRail)}>
<FileTreeNav
activeFileKey={activeFileKey}
groups={groups}
showGroupHeaders={showGroupHeaders}
onSelectFile={handleSelectFile}
/>
</Flexbox>
)}
</Flexbox>
)}
</Flexbox>
);
},
);
Review.displayName = 'AgentWorkingSidebarReview';
export default Review;