Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(review-panel): hover revert button to discard per-file working-tree changes (#14716)

Arvin Xu846e648fea9c
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index f2f098ce239..b55de4dd72f 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -1,5 +1,5 @@
import { execFile, spawn } from 'node:child_process';
-import { readFile, stat } from 'node:fs/promises';
+import { readFile, rm, stat } from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
@@ -11,6 +11,7 @@ import type {
GitBranchListItem,
GitCheckoutResult,
GitFileDiffStatus,
+ GitFileRevertResult,
GitLinkedPullRequestResult,
GitPullResult,
GitPushResult,
@@ -1106,4 +1107,70 @@ export default class GitController extends ControllerModule {
return { error: stderr || 'git push failed', success: false };
}
}
+
+ /**
+ * Revert a single working-tree change. Mirrors what "Discard changes" does
+ * in GitHub Desktop / VSCode SCM: restore the file to its HEAD state,
+ * dropping any unstaged / staged edits — and physically delete the file
+ * when it doesn't exist at HEAD (untracked or staged-add).
+ *
+ * Branch logic by HEAD presence:
+ * - present at HEAD → `git checkout HEAD -- <file>` (covers modified,
+ * deleted, staged-D — restores both index + worktree from HEAD)
+ * - absent at HEAD → `git rm --cached` (unstage if staged-A; silent
+ * no-op for untracked) + `fs.rm` to delete the file from disk
+ *
+ * filePath is the repo-relative path from `git status` output, the same
+ * shape we hand to the renderer in `GitWorkingTreePatch.filePath`. We
+ * reject absolute paths and `..` traversal so the renderer can't poke
+ * outside the repo even if its payload were tampered with.
+ */
+ @IpcMethod()
+ async revertGitFile(payload: { filePath: string; path: string }): Promise<GitFileRevertResult> {
+ const { path: dirPath, filePath } = payload;
+ if (!filePath?.trim()) return { error: 'File path is required', success: false };
+ if (path.isAbsolute(filePath) || filePath.split(/[/\\]/).includes('..')) {
+ return { error: `Invalid file path: ${filePath}`, success: false };
+ }
+
+ const execFileAsync = promisify(execFile);
+
+ // Probe HEAD via cat-file -e — exit 0 means the blob exists at HEAD.
+ let existsAtHead: boolean;
+ try {
+ await execFileAsync('git', ['cat-file', '-e', `HEAD:${filePath}`], {
+ cwd: dirPath,
+ timeout: 5000,
+ });
+ existsAtHead = true;
+ } catch {
+ existsAtHead = false;
+ }
+
+ try {
+ if (existsAtHead) {
+ await execFileAsync('git', ['checkout', 'HEAD', '--', filePath], {
+ cwd: dirPath,
+ timeout: 15_000,
+ });
+ } else {
+ // Unstage if the file is in the index (staged-add). `git rm --cached`
+ // exits non-zero on untracked paths, which is fine — swallow it.
+ try {
+ await execFileAsync('git', ['rm', '--cached', '--quiet', '--', filePath], {
+ cwd: dirPath,
+ timeout: 5000,
+ });
+ } catch {
+ // not staged — fall through to the disk-delete
+ }
+ await rm(path.resolve(dirPath, filePath), { force: true, recursive: false });
+ }
+ return { success: true };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ logger.debug('[revertGitFile] failed', { filePath, stderr });
+ return { error: stderr || 'git revert failed', success: false };
+ }
+ }
}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index aad2a92350f..f457df243c5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -891,6 +891,13 @@
"workingPanel.review.mode.unstaged": "Unstaged",
"workingPanel.review.more": "More options",
"workingPanel.review.refresh": "Refresh",
+ "workingPanel.review.revert": "Discard changes",
+ "workingPanel.review.revert.confirm.cancel": "Cancel",
+ "workingPanel.review.revert.confirm.description": "Working tree changes to {{filePath}} will be permanently discarded. Untracked files are deleted from disk.",
+ "workingPanel.review.revert.confirm.ok": "Discard",
+ "workingPanel.review.revert.confirm.title": "Discard changes to this file?",
+ "workingPanel.review.revert.failed": "Couldn't discard changes: {{error}}",
+ "workingPanel.review.revert.success": "Discarded changes to {{filePath}}",
"workingPanel.review.textDiff.disable": "Disable inline text diff",
"workingPanel.review.textDiff.enable": "Enable inline text diff",
"workingPanel.review.title": "Review",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index c269fb9d996..10509c6f63b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -891,6 +891,13 @@
"workingPanel.review.mode.unstaged": "未暂存",
"workingPanel.review.more": "更多选项",
"workingPanel.review.refresh": "同步",
+ "workingPanel.review.revert": "撤销变更",
+ "workingPanel.review.revert.confirm.cancel": "取消",
+ "workingPanel.review.revert.confirm.description": "{{filePath}} 的工作区变更将被永久丢弃,未跟踪的新文件会从磁盘删除。",
+ "workingPanel.review.revert.confirm.ok": "撤销",
+ "workingPanel.review.revert.confirm.title": "撤销此文件的变更?",
+ "workingPanel.review.revert.failed": "撤销失败:{{error}}",
+ "workingPanel.review.revert.success": "已撤销 {{filePath}} 的变更",
"workingPanel.review.textDiff.disable": "关闭文字差异",
"workingPanel.review.textDiff.enable": "启用文字差异",
"workingPanel.review.title": "审查",
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index 153feca4fd0..342d9a81407 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -123,6 +123,11 @@ export interface GitCheckoutResult {
success: boolean;
}
+export interface GitFileRevertResult {
+ error?: string;
+ success: boolean;
+}
+
export interface GitPullResult {
error?: string;
/** True when `git pull` reported the branch was already up-to-date */
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 1fffa0519f9..6d15d773335 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -948,6 +948,14 @@ export default {
'workingPanel.review.mode.unstaged': 'Unstaged',
'workingPanel.review.more': 'More options',
'workingPanel.review.refresh': 'Refresh',
+ 'workingPanel.review.revert': 'Discard changes',
+ 'workingPanel.review.revert.confirm.cancel': 'Cancel',
+ 'workingPanel.review.revert.confirm.description':
+ 'Working tree changes to {{filePath}} will be permanently discarded. Untracked files are deleted from disk.',
+ 'workingPanel.review.revert.confirm.ok': 'Discard',
+ 'workingPanel.review.revert.confirm.title': 'Discard changes to this file?',
+ 'workingPanel.review.revert.failed': "Couldn't discard changes: {{error}}",
+ 'workingPanel.review.revert.success': 'Discarded changes to {{filePath}}',
'workingPanel.review.textDiff.disable': 'Disable inline text diff',
'workingPanel.review.textDiff.enable': 'Enable inline text diff',
'workingPanel.review.title': 'Review',
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx
index de86d0ec69b..685054b8a54 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx
@@ -2,26 +2,31 @@
import type { GitFileDiffStatus } from '@lobechat/electron-client-ipc';
import { ActionIcon, copyToClipboard, PatchDiff } from '@lobehub/ui';
+import { Popconfirm } from 'antd';
import { createStaticStyles } from 'antd-style';
-import { CopyIcon } from 'lucide-react';
+import { CopyIcon, Undo2Icon } from 'lucide-react';
import path from 'path-browserify-esm';
-import { memo, type MouseEvent, useCallback } from 'react';
+import { memo, type MouseEvent, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
+import { electronGitService } from '@/services/electron/git';
const styles = createStaticStyles(({ css, cssVar }) => ({
additions: css`
color: ${cssVar.colorSuccess};
`,
- // Copy button stays hidden until the row is hovered so it doesn't add
- // visual noise to the long file list. Mirrors GitHub's "Files changed".
- copy: css`
+ // Hover-revealed row actions (copy / revert). Hidden until the row is
+ // hovered so the long file list stays visually quiet. While the revert
+ // Popconfirm is open we force-keep them visible — otherwise moving the
+ // cursor over the popover collapses the icons and the trigger jumps.
+ rowAction: css`
flex: none;
color: ${cssVar.colorTextTertiary};
opacity: 0;
transition: opacity 0.15s;
+ &[data-force-visible='true'],
&:focus-visible {
opacity: 1;
}
@@ -30,6 +35,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
opacity: 1;
}
`,
+ revertDanger: css`
+ &:hover {
+ color: ${cssVar.colorError};
+ }
+ `,
deletions: css`
color: ${cssVar.colorError};
`,
@@ -91,55 +101,122 @@ interface FileItemHeaderProps {
additions: number;
deletions: number;
filePath: string;
+ /** Called after a successful revert so the parent can refresh the patch list. */
+ onReverted?: () => void;
+ /** When provided, enables the per-file revert button (unstaged mode only). */
+ revertContext?: { workingDirectory: string };
// Status reserved for future use (e.g. dim deleted entries) — keep on the
// shape so the parent doesn't need to re-derive it later.
status: GitFileDiffStatus;
}
-export const FileItemHeader = memo<FileItemHeaderProps>(({ filePath, additions, deletions }) => {
- const { t } = useTranslation('chat');
-
- const lastSlash = filePath.lastIndexOf('/');
- const dir = lastSlash >= 0 ? filePath.slice(0, lastSlash + 1) : '';
- const fileName = lastSlash >= 0 ? filePath.slice(lastSlash + 1) : filePath;
-
- const handleCopy = useCallback(
- async (event: MouseEvent<HTMLDivElement>) => {
- // Stop propagation so the row doesn't toggle expand on copy click.
- event.stopPropagation();
- await copyToClipboard(filePath);
- message.success(t('workingPanel.review.copied'));
- },
- [filePath, t],
- );
-
- return (
- <span className={styles.header}>
- <span className={styles.pathWrapper} title={filePath}>
- {dir && (
- // bdi keeps the dir's visual order LTR while the span is
- // direction: rtl for head-side truncation of leading segments.
- <span className={styles.dir}>
- <bdi dir={'ltr'}>{dir}</bdi>
- </span>
+export const FileItemHeader = memo<FileItemHeaderProps>(
+ ({ filePath, additions, deletions, revertContext, onReverted }) => {
+ const { t } = useTranslation('chat');
+
+ const lastSlash = filePath.lastIndexOf('/');
+ const dir = lastSlash >= 0 ? filePath.slice(0, lastSlash + 1) : '';
+ const fileName = lastSlash >= 0 ? filePath.slice(lastSlash + 1) : filePath;
+
+ const handleCopy = useCallback(
+ async (event: MouseEvent<HTMLDivElement>) => {
+ // Stop propagation so the row doesn't toggle expand on copy click.
+ event.stopPropagation();
+ await copyToClipboard(filePath);
+ message.success(t('workingPanel.review.copied'));
+ },
+ [filePath, t],
+ );
+
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [reverting, setReverting] = useState(false);
+
+ const handleConfirmRevert = useCallback(async () => {
+ if (!revertContext) return;
+ setReverting(true);
+ try {
+ const result = await electronGitService.revertGitFile({
+ filePath,
+ path: revertContext.workingDirectory,
+ });
+ if (result.success) {
+ message.success(t('workingPanel.review.revert.success', { filePath }));
+ onReverted?.();
+ } else {
+ message.error(
+ t('workingPanel.review.revert.failed', {
+ error: result.error || 'unknown error',
+ }),
+ );
+ }
+ } catch (error: any) {
+ message.error(
+ t('workingPanel.review.revert.failed', {
+ error: error?.message || String(error),
+ }),
+ );
+ } finally {
+ setReverting(false);
+ setConfirmOpen(false);
+ }
+ }, [filePath, onReverted, revertContext, t]);
+
+ return (
+ <span className={styles.header}>
+ <span className={styles.pathWrapper} title={filePath}>
+ {dir && (
+ // bdi keeps the dir's visual order LTR while the span is
+ // direction: rtl for head-side truncation of leading segments.
+ <span className={styles.dir}>
+ <bdi dir={'ltr'}>{dir}</bdi>
+ </span>
+ )}
+ <span className={styles.fileName}>{fileName}</span>
+ </span>
+ <span className={styles.stats}>
+ {additions > 0 && <span className={styles.additions}>+{additions}</span>}
+ {additions > 0 && deletions > 0 && ' '}
+ {deletions > 0 && <span className={styles.deletions}>-{deletions}</span>}
+ </span>
+ {revertContext && (
+ <Popconfirm
+ arrow={false}
+ cancelText={t('workingPanel.review.revert.confirm.cancel')}
+ description={t('workingPanel.review.revert.confirm.description', { filePath })}
+ okButtonProps={{ danger: true, loading: reverting, type: 'primary' }}
+ okText={t('workingPanel.review.revert.confirm.ok')}
+ // Controlled open + onOpenChange lets antd handle outside-click /
+ // Esc to close while we still drive the click-to-open via the
+ // wrapper's stopPropagation (so the Collapse row doesn't toggle).
+ open={confirmOpen}
+ placement={'bottomRight'}
+ title={t('workingPanel.review.revert.confirm.title')}
+ onCancel={() => setConfirmOpen(false)}
+ onConfirm={handleConfirmRevert}
+ onOpenChange={setConfirmOpen}
+ >
+ <span onClick={(event) => event.stopPropagation()}>
+ <ActionIcon
+ className={`${styles.rowAction} ${styles.revertDanger}`}
+ data-force-visible={confirmOpen}
+ icon={Undo2Icon}
+ size={'small'}
+ title={t('workingPanel.review.revert')}
+ />
+ </span>
+ </Popconfirm>
)}
- <span className={styles.fileName}>{fileName}</span>
+ <ActionIcon
+ className={styles.rowAction}
+ icon={CopyIcon}
+ size={'small'}
+ title={t('workingPanel.review.copyPath')}
+ onClick={handleCopy}
+ />
</span>
- <span className={styles.stats}>
- {additions > 0 && <span className={styles.additions}>+{additions}</span>}
- {additions > 0 && deletions > 0 && ' '}
- {deletions > 0 && <span className={styles.deletions}>-{deletions}</span>}
- </span>
- <ActionIcon
- className={styles.copy}
- icon={CopyIcon}
- size={'small'}
- title={t('workingPanel.review.copyPath')}
- onClick={handleCopy}
- />
- </span>
- );
-});
+ );
+ },
+);
FileItemHeader.displayName = 'ReviewFileItemHeader';
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
index 36e76dd0a0b..3437d975eb4 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
@@ -283,6 +283,10 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {
additions={entry.additions}
deletions={entry.deletions}
filePath={entry.filePath}
+ onReverted={() => void mutate()}
+ // Revert is only meaningful for working-tree changes; in branch-diff
+ // mode there's nothing to "discard" on the file system.
+ revertContext={mode === 'unstaged' ? { workingDirectory } : undefined}
status={entry.status}
/>
),
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 3e578b4ef89..a2cfe7a544a 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -5,6 +5,7 @@ import {
type GitBranchInfo,
type GitBranchListItem,
type GitCheckoutResult,
+ type GitFileRevertResult,
type GitLinkedPullRequestResult,
type GitPullResult,
type GitPushResult,
@@ -84,6 +85,10 @@ class ElectronGitService {
async pushGitBranch(params: { path: string }): Promise<GitPushResult> {
return this.ipc.git.pushGitBranch(params);
}
+
+ async revertGitFile(params: { filePath: string; path: string }): Promise<GitFileRevertResult> {
+ return this.ipc.git.revertGitFile(params);
+ }
}
export const electronGitService = new ElectronGitService();