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.

✨ feat(git-status): one-click pull/push from branch chip (#14041)

Arvin Xu2a3667493f20
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 50f8d537040..6ff6d487e1b 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -9,6 +9,8 @@ import type {
GitBranchListItem,
GitCheckoutResult,
GitLinkedPullRequestResult,
+ GitPullResult,
+ GitPushResult,
GitWorkingTreeFiles,
GitWorkingTreeStatus,
} from '@lobechat/electron-client-ipc';
@@ -263,10 +265,24 @@ export default class GitController extends ControllerModule {
* Count commits HEAD is ahead/behind its upstream tracking ref.
* Returns `hasUpstream: false` when the branch has no upstream configured
* (e.g. local-only branches, or after the remote branch is deleted).
+ *
+ * Does a best-effort `git fetch` first so the result reflects what's
+ * actually on the remote — the renderer calls this via SWR with
+ * `revalidateOnFocus`, so the fetch piggybacks on window re-focus. Fetch
+ * failures (offline, no credentials, no `origin` remote) are swallowed so
+ * we still return whatever can be computed against the cached refs.
*/
@IpcMethod()
async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {
const execFileAsync = promisify(execFile);
+ try {
+ await execFileAsync('git', ['fetch', '--no-tags', '--quiet', 'origin'], {
+ cwd: dirPath,
+ timeout: 10_000,
+ });
+ } catch {
+ // swallow — fall through to compute against cached refs
+ }
try {
const { stdout: upstreamOut } = await execFileAsync(
'git',
@@ -284,7 +300,36 @@ export default class GitController extends ControllerModule {
const [behindStr, aheadStr] = stdout.trim().split(/\s+/);
const behind = Number.parseInt(behindStr ?? '0', 10) || 0;
const ahead = Number.parseInt(aheadStr ?? '0', 10) || 0;
- return { ahead, behind, hasUpstream: true, upstream };
+
+ // `git push -u origin HEAD` always targets origin/<current-branch-name>,
+ // which may differ from upstream (the branched-off-canary case).
+ let pushTarget: string | undefined;
+ let pushTargetExists = false;
+ try {
+ const { stdout: branchOut } = await execFileAsync(
+ 'git',
+ ['symbolic-ref', '--short', 'HEAD'],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ const branch = branchOut.trim();
+ if (branch) {
+ pushTarget = `origin/${branch}`;
+ try {
+ await execFileAsync(
+ 'git',
+ ['rev-parse', '--verify', '--quiet', `refs/remotes/${pushTarget}`],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ pushTargetExists = true;
+ } catch {
+ pushTargetExists = false;
+ }
+ }
+ } catch {
+ // detached HEAD — leave pushTarget undefined
+ }
+
+ return { ahead, behind, hasUpstream: true, pushTarget, pushTargetExists, upstream };
} catch {
// No upstream configured, detached HEAD, or git error — all treated as "no upstream"
return { ahead: 0, behind: 0, hasUpstream: false };
@@ -322,4 +367,54 @@ export default class GitController extends ControllerModule {
return { error: stderr || 'git checkout failed', success: false };
}
}
+
+ /**
+ * Pull the current branch's upstream via fast-forward only.
+ *
+ * `--ff-only` avoids creating accidental merge commits when the local branch
+ * has diverged — in that case the user should resolve merge/rebase in their
+ * own terminal. For the common "just behind" case this is a safe one-click.
+ */
+ @IpcMethod()
+ async pullGitBranch(payload: { path: string }): Promise<GitPullResult> {
+ const { path: dirPath } = payload;
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stdout } = await execFileAsync('git', ['pull', '--ff-only'], {
+ cwd: dirPath,
+ timeout: 60_000,
+ });
+ const noop = /Already up to date/i.test(stdout);
+ return { noop, success: true };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ logger.debug('[pullGitBranch] failed', { stderr });
+ return { error: stderr || 'git pull failed', success: false };
+ }
+ }
+
+ /**
+ * Push the current branch to its same-named remote on `origin`.
+ *
+ * Uses `git push -u origin HEAD` instead of plain `git push` so the action
+ * works even when local branch name differs from the configured upstream
+ */
+ @IpcMethod()
+ async pushGitBranch(payload: { path: string }): Promise<GitPushResult> {
+ const { path: dirPath } = payload;
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stderr } = await execFileAsync('git', ['push', '-u', 'origin', 'HEAD'], {
+ cwd: dirPath,
+ timeout: 60_000,
+ });
+ // git push writes progress/status to stderr even on success
+ const noop = /Everything up-to-date/i.test(stderr);
+ return { noop, success: true };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ logger.debug('[pushGitBranch] failed', { stderr });
+ return { error: stderr || 'git push failed', success: false };
+ }
+ }
}
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index f00312e743c..18e6d22eb5a 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -438,9 +438,6 @@
"loading.plugin": "Skill running…",
"localSystem.workingDirectory.agentDescription": "Default working directory for all conversations with this Agent",
"localSystem.workingDirectory.agentLevel": "Agent Working Directory",
- "localSystem.workingDirectory.aheadBehindTooltip": "{{ahead}} to push · {{behind}} to pull ({{upstream}})",
- "localSystem.workingDirectory.aheadTooltip": "{{count}} commit(s) to push to {{upstream}}",
- "localSystem.workingDirectory.behindTooltip": "{{count}} commit(s) to pull from {{upstream}}",
"localSystem.workingDirectory.branchSearchPlaceholder": "Search branches",
"localSystem.workingDirectory.branchesEmpty": "No local branches",
"localSystem.workingDirectory.branchesHeading": "Branches",
@@ -465,6 +462,17 @@
"localSystem.workingDirectory.notSet": "Click to set working directory",
"localSystem.workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects",
"localSystem.workingDirectory.prTooltipWithExtra": "{{title}} (+{{count}} more open PR on this branch)",
+ "localSystem.workingDirectory.pullAction": "Click to pull {{count}} commit(s) from {{upstream}}",
+ "localSystem.workingDirectory.pullFailed": "Pull failed",
+ "localSystem.workingDirectory.pullInProgress": "Pulling…",
+ "localSystem.workingDirectory.pullNoop": "Already up to date",
+ "localSystem.workingDirectory.pullSuccess": "Pulled successfully",
+ "localSystem.workingDirectory.pushAction": "Click to push {{count}} commit(s) to {{target}}",
+ "localSystem.workingDirectory.pushActionNew": "Click to create branch {{target}}",
+ "localSystem.workingDirectory.pushFailed": "Push failed",
+ "localSystem.workingDirectory.pushInProgress": "Pushing…",
+ "localSystem.workingDirectory.pushNoop": "Everything up-to-date",
+ "localSystem.workingDirectory.pushSuccess": "Pushed successfully",
"localSystem.workingDirectory.recent": "Recent",
"localSystem.workingDirectory.refreshGitStatus": "Refresh branch & PR status",
"localSystem.workingDirectory.removeRecent": "Remove from recent",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index ef2a1549e82..d0367ef8098 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -438,9 +438,6 @@
"loading.plugin": "技能运行中…",
"localSystem.workingDirectory.agentDescription": "该助手下所有对话的默认工作目录",
"localSystem.workingDirectory.agentLevel": "代理工作目录",
- "localSystem.workingDirectory.aheadBehindTooltip": "待推送 {{ahead}} · 待拉取 {{behind}}({{upstream}})",
- "localSystem.workingDirectory.aheadTooltip": "{{count}} 个提交待推送到 {{upstream}}",
- "localSystem.workingDirectory.behindTooltip": "{{count}} 个提交待从 {{upstream}} 拉取",
"localSystem.workingDirectory.branchSearchPlaceholder": "搜索分支",
"localSystem.workingDirectory.branchesEmpty": "暂无本地分支",
"localSystem.workingDirectory.branchesHeading": "分支",
@@ -465,6 +462,17 @@
"localSystem.workingDirectory.notSet": "点击设置工作目录",
"localSystem.workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects",
"localSystem.workingDirectory.prTooltipWithExtra": "{{title}}(此分支还有 {{count}} 个开放 PR)",
+ "localSystem.workingDirectory.pullAction": "点击从 {{upstream}} 拉取 {{count}} 个提交",
+ "localSystem.workingDirectory.pullFailed": "拉取失败",
+ "localSystem.workingDirectory.pullInProgress": "拉取中…",
+ "localSystem.workingDirectory.pullNoop": "已是最新",
+ "localSystem.workingDirectory.pullSuccess": "拉取成功",
+ "localSystem.workingDirectory.pushAction": "点击推送 {{count}} 个提交到 {{target}}",
+ "localSystem.workingDirectory.pushActionNew": "点击创建 {{target}} 分支",
+ "localSystem.workingDirectory.pushFailed": "推送失败",
+ "localSystem.workingDirectory.pushInProgress": "推送中…",
+ "localSystem.workingDirectory.pushNoop": "已是最新",
+ "localSystem.workingDirectory.pushSuccess": "推送成功",
"localSystem.workingDirectory.recent": "最近使用",
"localSystem.workingDirectory.refreshGitStatus": "刷新分支与 PR 状态",
"localSystem.workingDirectory.removeRecent": "从最近目录中移除",
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
new file mode 100644
index 00000000000..0a746f96a27
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -0,0 +1,91 @@
+export interface GitBranchInfo {
+ /** Branch short name, or short SHA when in detached HEAD state */
+ branch?: string;
+ /** True when HEAD is detached (no branch ref) */
+ detached?: boolean;
+}
+
+export interface GitLinkedPullRequest {
+ number: number;
+ state: string;
+ title: string;
+ url: string;
+}
+
+export interface GitLinkedPullRequestResult {
+ /** Additional open PRs targeting the same head branch, beyond the primary one */
+ extraCount?: number;
+ /** Null when no open PR is linked to the branch */
+ pullRequest: GitLinkedPullRequest | null;
+ /** 'ok' — lookup succeeded; 'gh-missing' — gh CLI unavailable / not authed; 'error' — other failure */
+ status: 'ok' | 'gh-missing' | 'error';
+}
+
+export interface GitBranchListItem {
+ current: boolean;
+ name: string;
+ upstream?: string;
+}
+
+export interface GitWorkingTreeStatus {
+ /** Untracked + staged-as-added files */
+ added: number;
+ clean: boolean;
+ /** Files marked deleted in either index or working tree */
+ deleted: number;
+ /** Modified / renamed / copied / type-changed / unmerged files */
+ modified: number;
+ /** Total dirty files (each file counted once) — sum of added + modified + deleted */
+ total: number;
+}
+
+export interface GitWorkingTreeFiles {
+ /** Repo-relative paths for untracked + staged-as-added files */
+ added: string[];
+ /** Repo-relative paths for files marked deleted in either index or working tree */
+ deleted: string[];
+ /** Repo-relative paths for modified / renamed / copied / type-changed / unmerged files */
+ modified: string[];
+}
+
+export interface GitCheckoutResult {
+ error?: string;
+ success: boolean;
+}
+
+export interface GitPullResult {
+ error?: string;
+ /** True when `git pull` reported the branch was already up-to-date */
+ noop?: boolean;
+ success: boolean;
+}
+
+export interface GitPushResult {
+ error?: string;
+ /** True when `git push` reported everything is already up-to-date */
+ noop?: boolean;
+ success: boolean;
+}
+
+export interface GitAheadBehind {
+ /** Commits in HEAD not in upstream — push count */
+ ahead: number;
+ /** Commits in upstream not in HEAD — pull count */
+ behind: number;
+ /** True when the branch has an upstream tracking ref configured */
+ hasUpstream: boolean;
+ /**
+ * Ref the one-click push action would actually target — always
+ * `origin/<current-branch-name>`, because we use `git push -u origin HEAD`.
+ * May differ from `upstream` (e.g. branch created via
+ * `git checkout -b feat/x origin/canary`). Undefined when detached.
+ */
+ pushTarget?: string;
+ /**
+ * True when `pushTarget` already exists as a remote-tracking ref. False
+ * means clicking push would create a new remote branch.
+ */
+ pushTargetExists?: boolean;
+ /** Upstream ref short name (e.g. `origin/main`), when available */
+ upstream?: string;
+}
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index 16863e39338..1d71461d513 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,4 +1,5 @@
export * from './dataSync';
+export * from './git';
export * from './localSystem';
export * from './mcpInstall';
export * from './notification';
diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.ts
index 3dc859dfc6f..d29c07a1d90 100644
--- a/packages/electron-client-ipc/src/types/system.ts
+++ b/packages/electron-client-ipc/src/types/system.ts
@@ -27,69 +27,3 @@ export interface UserPathData {
export type ThemeMode = 'system' | 'dark' | 'light';
export type ThemeAppearance = 'dark' | 'light' | string;
-
-export interface GitBranchInfo {
- /** Branch short name, or short SHA when in detached HEAD state */
- branch?: string;
- /** True when HEAD is detached (no branch ref) */
- detached?: boolean;
-}
-
-export interface GitLinkedPullRequest {
- number: number;
- state: string;
- title: string;
- url: string;
-}
-
-export interface GitLinkedPullRequestResult {
- /** Additional open PRs targeting the same head branch, beyond the primary one */
- extraCount?: number;
- /** Null when no open PR is linked to the branch */
- pullRequest: GitLinkedPullRequest | null;
- /** 'ok' — lookup succeeded; 'gh-missing' — gh CLI unavailable / not authed; 'error' — other failure */
- status: 'ok' | 'gh-missing' | 'error';
-}
-
-export interface GitBranchListItem {
- current: boolean;
- name: string;
- upstream?: string;
-}
-
-export interface GitWorkingTreeStatus {
- /** Untracked + staged-as-added files */
- added: number;
- clean: boolean;
- /** Files marked deleted in either index or working tree */
- deleted: number;
- /** Modified / renamed / copied / type-changed / unmerged files */
- modified: number;
- /** Total dirty files (each file counted once) — sum of added + modified + deleted */
- total: number;
-}
-
-export interface GitWorkingTreeFiles {
- /** Repo-relative paths for untracked + staged-as-added files */
- added: string[];
- /** Repo-relative paths for files marked deleted in either index or working tree */
- deleted: string[];
- /** Repo-relative paths for modified / renamed / copied / type-changed / unmerged files */
- modified: string[];
-}
-
-export interface GitCheckoutResult {
- error?: string;
- success: boolean;
-}
-
-export interface GitAheadBehind {
- /** Commits in HEAD not in upstream — push count */
- ahead: number;
- /** Commits in upstream not in HEAD — pull count */
- behind: number;
- /** True when the branch has an upstream tracking ref configured */
- hasUpstream: boolean;
- /** Upstream ref short name (e.g. `origin/main`), when available */
- upstream?: string;
-}
diff --git a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
index 966a901dd37..2f409ec2858 100644
--- a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
+++ b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
@@ -4,6 +4,9 @@ import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucid
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { message } from '@/components/AntdStaticMethods';
+import RingLoadingIcon from '@/components/RingLoading';
+import { electronGitService } from '@/services/electron/git';
import { electronSystemService } from '@/services/electron/system';
import BranchSwitcher from './BranchSwitcher';
@@ -12,93 +15,124 @@ import { useGitInfo } from './useGitInfo';
import { useWorkingTreeStatus } from './useWorkingTreeStatus';
import WorkingTreeFilesContent from './WorkingTreeFilesContent';
-const styles = createStaticStyles(({ css }) => ({
- aheadBehindItem: css`
- display: inline-flex;
- gap: 0;
- align-items: center;
-
- margin-inline-start: -2px;
-
- font-variant-numeric: tabular-nums;
- line-height: 1;
- `,
- aheadStat: css`
- color: ${cssVar.colorInfo};
- `,
- behindStat: css`
- color: ${cssVar.colorError};
- `,
- branchLabel: css`
- overflow: hidden;
- max-width: 160px;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- diffStat: css`
- display: inline-flex;
- flex-shrink: 0;
- gap: 4px;
- align-items: center;
-
- font-variant-numeric: tabular-nums;
- `,
- diffStatAdded: css`
- color: ${cssVar.colorSuccess};
- `,
- diffStatDeleted: css`
- color: ${cssVar.colorError};
- `,
- diffStatModified: css`
- color: ${cssVar.colorWarning};
- `,
- prTrigger: css`
- cursor: pointer;
-
- display: flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
- border-radius: 4px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- transition: background 0.2s;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillTertiary};
- }
- `,
- separator: css`
- width: 1px;
- height: 10px;
- background: ${cssVar.colorSplit};
- `,
- trigger: css`
- cursor: pointer;
-
- display: flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 4px;
- border-radius: 4px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- transition: background 0.2s;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
-}));
+const styles = createStaticStyles(({ css }) => {
+ return {
+ aheadBehindStat: css`
+ display: inline-flex;
+ gap: 0;
+ align-items: center;
+
+ margin-inline-start: -2px;
+
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+ `,
+ aheadStat: css`
+ color: ${cssVar.colorInfo};
+ `,
+ behindStat: css`
+ color: ${cssVar.colorError};
+ `,
+ branchLabel: css`
+ overflow: hidden;
+ max-width: 160px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ diffStat: css`
+ display: inline-flex;
+ flex-shrink: 0;
+ gap: 4px;
+ align-items: center;
+
+ font-variant-numeric: tabular-nums;
+ `,
+ diffStatAdded: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ diffStatDeleted: css`
+ color: ${cssVar.colorError};
+ `,
+ diffStatModified: css`
+ color: ${cssVar.colorWarning};
+ `,
+ prTrigger: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ transition: background 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ separator: css`
+ width: 1px;
+ height: 10px;
+ background: ${cssVar.colorSplit};
+ `,
+ syncTrigger: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 2px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ syncTriggerDisabled: css`
+ cursor: progress;
+ opacity: 0.6;
+
+ &:hover {
+ background: transparent;
+ }
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ };
+});
interface GitStatusProps {
isGithub: boolean;
@@ -112,6 +146,8 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
const { data: aheadBehind, mutate: mutateAheadBehind } = useGitAheadBehind(path);
const [switcherOpen, setSwitcherOpen] = useState(false);
const [filesOpen, setFilesOpen] = useState(false);
+ const [pulling, setPulling] = useState(false);
+ const [pushing, setPushing] = useState(false);
const handleOpenPr = useCallback(() => {
if (data?.pullRequest?.url) {
@@ -119,6 +155,52 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
}
}, [data?.pullRequest?.url]);
+ const refreshAfterSync = useCallback(async () => {
+ await Promise.all([mutate(), mutateWorkingStatus(), mutateAheadBehind()]);
+ }, [mutate, mutateWorkingStatus, mutateAheadBehind]);
+
+ const syncBusy = pulling || pushing;
+
+ const handlePull = useCallback(async () => {
+ if (pulling || pushing) return;
+ setPulling(true);
+ try {
+ const result = await electronGitService.pullGitBranch({ path });
+ if (result.success) {
+ if (result.noop) {
+ message.info(t('localSystem.workingDirectory.pullNoop'));
+ } else {
+ message.success(t('localSystem.workingDirectory.pullSuccess'));
+ }
+ await refreshAfterSync();
+ } else {
+ message.error(result.error || t('localSystem.workingDirectory.pullFailed'));
+ }
+ } finally {
+ setPulling(false);
+ }
+ }, [path, pulling, pushing, refreshAfterSync, t]);
+
+ const handlePush = useCallback(async () => {
+ if (pulling || pushing) return;
+ setPushing(true);
+ try {
+ const result = await electronGitService.pushGitBranch({ path });
+ if (result.success) {
+ if (result.noop) {
+ message.info(t('localSystem.workingDirectory.pushNoop'));
+ } else {
+ message.success(t('localSystem.workingDirectory.pushSuccess'));
+ }
+ await refreshAfterSync();
+ } else {
+ message.error(result.error || t('localSystem.workingDirectory.pushFailed'));
+ }
+ } finally {
+ setPushing(false);
+ }
+ }, [path, pulling, pushing, refreshAfterSync, t]);
+
if (!data?.branch) return null;
const branchTooltip = data.detached
@@ -149,70 +231,88 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
const showAhead = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.ahead > 0;
const showBehind = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.behind > 0;
const upstreamName = aheadBehind?.upstream ?? '';
- const aheadBehindTooltip =
- showAhead && showBehind
- ? t('localSystem.workingDirectory.aheadBehindTooltip', {
- ahead: aheadBehind!.ahead,
- behind: aheadBehind!.behind,
- upstream: upstreamName,
- })
- : showAhead
- ? t('localSystem.workingDirectory.aheadTooltip', {
- count: aheadBehind!.ahead,
- upstream: upstreamName,
- })
- : showBehind
- ? t('localSystem.workingDirectory.behindTooltip', {
- count: aheadBehind!.behind,
- upstream: upstreamName,
- })
- : undefined;
-
- const combinedBranchTooltip =
- branchTooltip && aheadBehindTooltip
- ? `${branchTooltip} · ${aheadBehindTooltip}`
- : (branchTooltip ?? aheadBehindTooltip);
+ const pushTargetName = aheadBehind?.pushTarget ?? '';
+ const pushTargetExists = !!aheadBehind?.pushTargetExists;
const branchTrigger = (
<div className={styles.trigger}>
<Icon icon={GitBranchIcon} size={12} />
<span className={styles.branchLabel}>{data.branch}</span>
- {showBehind && (
- <span className={`${styles.aheadBehindItem} ${styles.behindStat}`}>
- <Icon icon={ArrowDownIcon} size={10} />
- {aheadBehind!.behind}
- </span>
- )}
- {showAhead && (
- <span className={`${styles.aheadBehindItem} ${styles.aheadStat}`}>
- <Icon icon={ArrowUpIcon} size={10} />
- {aheadBehind!.ahead}
- </span>
- )}
</div>
);
const branchNode = data.detached ? (
- <Tooltip title={combinedBranchTooltip}>{branchTrigger}</Tooltip>
+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
) : (
<BranchSwitcher
currentBranch={data.branch}
open={switcherOpen}
path={path}
+ onExternalRefresh={refreshAfterSync}
onOpenChange={setSwitcherOpen}
onAfterCheckout={() => {
void mutate();
void mutateWorkingStatus();
void mutateAheadBehind();
}}
- onExternalRefresh={async () => {
- await Promise.all([mutate(), mutateWorkingStatus(), mutateAheadBehind()]);
- }}
>
- <Tooltip title={combinedBranchTooltip}>{branchTrigger}</Tooltip>
+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
</BranchSwitcher>
);
+ const pullTooltip = pulling
+ ? t('localSystem.workingDirectory.pullInProgress')
+ : t('localSystem.workingDirectory.pullAction', {
+ count: aheadBehind?.behind ?? 0,
+ upstream: upstreamName,
+ });
+
+ const pushTooltip = pushing
+ ? t('localSystem.workingDirectory.pushInProgress')
+ : t(
+ pushTargetExists
+ ? 'localSystem.workingDirectory.pushAction'
+ : 'localSystem.workingDirectory.pushActionNew',
+ {
+ count: aheadBehind?.ahead ?? 0,
+ target: pushTargetName || upstreamName,
+ },
+ );
+
+ const pullNode = showBehind && (
+ <Tooltip title={pullTooltip}>
+ <div
+ aria-busy={pulling}
+ aria-disabled={syncBusy}
+ className={`${styles.syncTrigger} ${styles.behindStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ role="button"
+ onClick={syncBusy ? undefined : handlePull}
+ >
+ <span className={styles.aheadBehindStat}>
+ {pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}
+ {aheadBehind!.behind}
+ </span>
+ </div>
+ </Tooltip>
+ );
+
+ const pushNode = showAhead && (
+ <Tooltip title={pushTooltip}>
+ <div
+ aria-busy={pushing}
+ aria-disabled={syncBusy}
+ className={`${styles.syncTrigger} ${styles.aheadStat} ${syncBusy ? styles.syncTriggerDisabled : ''}`}
+ role="button"
+ onClick={syncBusy ? undefined : handlePush}
+ >
+ <span className={styles.aheadBehindStat}>
+ {pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}
+ {aheadBehind!.ahead}
+ </span>
+ </div>
+ </Tooltip>
+ );
+
const diffNode = (() => {
if (!hasChanges || !workingStatus) return null;
const diffButton = (
@@ -251,6 +351,8 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
<>
<div className={styles.separator} />
{branchNode}
+ {pullNode}
+ {pushNode}
{diffNode}
{data.pullRequest && (
<>
diff --git a/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts b/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts
index 0ab31677154..ef54752c7f5 100644
--- a/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts
+++ b/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts
@@ -5,9 +5,10 @@ import { electronGitService } from '@/services/electron/git';
/**
* Ahead/behind commit counts for the current branch vs its upstream tracking ref.
- * Shown as push (↑) / pull (↓) badges in the status bar. Network-free: runs
- * `git rev-list` locally against already-fetched refs, so freshness depends on
- * whether the user has fetched recently — we don't auto-fetch here.
+ * Shown as push (↑) / pull (↓) badges in the status bar. Piggybacks a
+ * best-effort `git fetch` on every SWR load (including focus revalidation)
+ * inside the IPC, so remote updates surface when the user switches back to
+ * the window without needing a manual fetch.
*/
export const useGitAheadBehind = (dirPath?: string) => {
const key = isDesktop && dirPath ? ['git-ahead-behind', dirPath] : null;
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index e4544e874a9..948f1e4c333 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -455,10 +455,17 @@ export default {
'localSystem.workingDirectory.createBranchAction': 'Checkout new branch…',
'localSystem.workingDirectory.current': 'Current working directory',
'localSystem.workingDirectory.chooseDifferentFolder': 'Choose a different folder',
- 'localSystem.workingDirectory.aheadBehindTooltip':
- '{{ahead}} to push · {{behind}} to pull ({{upstream}})',
- 'localSystem.workingDirectory.aheadTooltip': '{{count}} commit(s) to push to {{upstream}}',
- 'localSystem.workingDirectory.behindTooltip': '{{count}} commit(s) to pull from {{upstream}}',
+ 'localSystem.workingDirectory.pullAction': 'Click to pull {{count}} commit(s) from {{upstream}}',
+ 'localSystem.workingDirectory.pullInProgress': 'Pulling…',
+ 'localSystem.workingDirectory.pullSuccess': 'Pulled successfully',
+ 'localSystem.workingDirectory.pullNoop': 'Already up to date',
+ 'localSystem.workingDirectory.pullFailed': 'Pull failed',
+ 'localSystem.workingDirectory.pushAction': 'Click to push {{count}} commit(s) to {{target}}',
+ 'localSystem.workingDirectory.pushActionNew': 'Click to create branch {{target}}',
+ 'localSystem.workingDirectory.pushInProgress': 'Pushing…',
+ 'localSystem.workingDirectory.pushSuccess': 'Pushed successfully',
+ 'localSystem.workingDirectory.pushNoop': 'Everything up-to-date',
+ 'localSystem.workingDirectory.pushFailed': 'Push failed',
'localSystem.workingDirectory.detachedHead': 'Detached HEAD at {{sha}}',
'localSystem.workingDirectory.diffStatTooltip':
'Added {{added}} · Modified {{modified}} · Deleted {{deleted}}',
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 24f285f803d..8a6b0daf1d2 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -4,6 +4,8 @@ import {
type GitBranchListItem,
type GitCheckoutResult,
type GitLinkedPullRequestResult,
+ type GitPullResult,
+ type GitPushResult,
type GitWorkingTreeFiles,
type GitWorkingTreeStatus,
} from '@lobechat/electron-client-ipc';
@@ -58,6 +60,14 @@ class ElectronGitService {
}): Promise<GitCheckoutResult> {
return this.ipc.git.checkoutGitBranch(params);
}
+
+ async pullGitBranch(params: { path: string }): Promise<GitPullResult> {
+ return this.ipc.git.pullGitBranch(params);
+ }
+
+ async pushGitBranch(params: { path: string }): Promise<GitPushResult> {
+ return this.ipc.git.pushGitBranch(params);
+ }
}
export const electronGitService = new ElectronGitService();