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(chat-input): branch ahead/behind badge + GitCtr refactor (#13980)

Arvin Xua0471d590624
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
new file mode 100644
index 00000000000..50f8d537040
--- /dev/null
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -0,0 +1,325 @@
+import { execFile } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import type {
+ GitAheadBehind,
+ GitBranchInfo,
+ GitBranchListItem,
+ GitCheckoutResult,
+ GitLinkedPullRequestResult,
+ GitWorkingTreeFiles,
+ GitWorkingTreeStatus,
+} from '@lobechat/electron-client-ipc';
+
+import { detectRepoType, resolveGitDir } from '@/utils/git';
+import { createLogger } from '@/utils/logger';
+
+import { ControllerModule, IpcMethod } from './index';
+
+const logger = createLogger('controllers:GitCtr');
+
+export default class GitController extends ControllerModule {
+ static override readonly groupName = 'git';
+
+ @IpcMethod()
+ async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {
+ return detectRepoType(dirPath);
+ }
+
+ /**
+ * Read current git branch from `.git/HEAD`. Returns short sha on detached HEAD.
+ * Handles both standard `.git` directories and `.git` worktree pointer files.
+ */
+ @IpcMethod()
+ async getGitBranch(dirPath: string): Promise<GitBranchInfo> {
+ try {
+ const gitDir = await resolveGitDir(dirPath);
+ if (!gitDir) return {};
+
+ const head = (await readFile(path.join(gitDir, 'HEAD'), 'utf8')).trim();
+ const refMatch = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
+ if (refMatch) {
+ return { branch: refMatch[1] };
+ }
+ // Detached HEAD — HEAD file contains the full sha
+ if (/^[\da-f]{40}$/i.test(head)) {
+ return { branch: head.slice(0, 7), detached: true };
+ }
+ return {};
+ } catch {
+ return {};
+ }
+ }
+
+ /**
+ * Query `gh` CLI for an open pull request whose head branch matches `branch`.
+ * Returns status = 'gh-missing' when `gh` is not installed / not authenticated,
+ * so the UI can render a helpful tooltip instead of an error.
+ */
+ @IpcMethod()
+ async getLinkedPullRequest(payload: {
+ branch: string;
+ path: string;
+ }): Promise<GitLinkedPullRequestResult> {
+ const { path: dirPath, branch } = payload;
+ if (!branch) {
+ return { pullRequest: null, status: 'ok' };
+ }
+
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stdout } = await execFileAsync(
+ 'gh',
+ [
+ 'pr',
+ 'list',
+ '--head',
+ branch,
+ '--state',
+ 'open',
+ '--limit',
+ '5',
+ '--json',
+ 'number,url,title,state',
+ ],
+ { cwd: dirPath, timeout: 8000 },
+ );
+ const parsed = JSON.parse(stdout.trim() || '[]') as Array<{
+ number: number;
+ state: string;
+ title: string;
+ url: string;
+ }>;
+ if (parsed.length === 0) {
+ return { pullRequest: null, status: 'ok' };
+ }
+ const [primary, ...rest] = parsed;
+ return {
+ extraCount: rest.length,
+ pullRequest: primary,
+ status: 'ok',
+ };
+ } catch (error: any) {
+ const code = error?.code;
+ const stderr: string = error?.stderr ?? '';
+ // `gh` binary not on PATH
+ if (code === 'ENOENT') {
+ return { pullRequest: null, status: 'gh-missing' };
+ }
+ // gh reports auth issues via stderr; treat as a soft-fail
+ if (/auth\s+login|not\s+logged\s+in|authentication/i.test(stderr)) {
+ return { pullRequest: null, status: 'gh-missing' };
+ }
+ logger.debug('[getLinkedPullRequest] failed', { branch, code, stderr });
+ return { pullRequest: null, status: 'error' };
+ }
+ }
+
+ /**
+ * List local git branches ordered by most recent commit.
+ * `current` is true for the checked-out branch.
+ */
+ @IpcMethod()
+ async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ [
+ 'for-each-ref',
+ '--sort=-committerdate',
+ '--format=%(HEAD)%09%(refname:short)%09%(upstream:short)',
+ 'refs/heads',
+ ],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ return stdout
+ .replaceAll('\r', '')
+ .split('\n')
+ .filter((line) => line.length > 0)
+ .map((line) => {
+ // Line format: "<HEAD-marker>\t<branch>\t<upstream>" where HEAD-marker is '*' or ' '
+ const [head, name, upstream] = line.split('\t');
+ return {
+ current: head === '*',
+ name: name ?? '',
+ upstream: upstream || undefined,
+ };
+ })
+ .filter((b) => b.name);
+ } catch (error: any) {
+ logger.warn('[listGitBranches] git command failed', {
+ code: error?.code,
+ cwd: dirPath,
+ message: error?.message,
+ stderr: error?.stderr?.toString?.() ?? error?.stderr,
+ });
+ return [];
+ }
+ }
+
+ /**
+ * Bucket dirty files into added / modified / deleted via `git status --porcelain -z`.
+ * Each file is counted once: untracked (`??`) and staged-add (`A`) → added,
+ * any `D` in index or working tree → deleted, everything else (`M`/`R`/`C`/`T`/`U`) → modified.
+ *
+ * Uses `-z` so paths are NUL-terminated (no C-style quoting, no `\n` splitting bugs).
+ * Rename/copy entries (`R`/`C`) emit two NUL-separated tokens — dest path then source
+ * path — so the source token must be consumed to keep counts correct.
+ */
+ @IpcMethod()
+ async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stdout } = await execFileAsync('git', ['status', '--porcelain', '-z'], {
+ cwd: dirPath,
+ timeout: 5000,
+ });
+ const tokens = stdout.split('\0');
+ let added = 0;
+ let modified = 0;
+ let deleted = 0;
+ let i = 0;
+ while (i < tokens.length) {
+ const entry = tokens[i];
+ i++;
+ if (entry.length < 2) continue;
+ const x = entry[0];
+ const y = entry[1];
+ // R/C entries carry an extra source-path token we must consume.
+ if (x === 'R' || x === 'C') i++;
+ if (x === '?' && y === '?') {
+ added++;
+ } else if (x === '!' && y === '!') {
+ // ignored — skip
+ } else if (x === 'D' || y === 'D') {
+ deleted++;
+ } else if (x === 'A' || y === 'A') {
+ added++;
+ } else {
+ modified++;
+ }
+ }
+ const total = added + modified + deleted;
+ return { added, clean: total === 0, deleted, modified, total };
+ } catch {
+ return { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
+ }
+ }
+
+ /**
+ * Return dirty file paths bucketed into added / modified / deleted.
+ * Same classification as getGitWorkingTreeStatus, but with per-file paths.
+ *
+ * Uses `git status --porcelain -z` so paths are NUL-terminated and never C-quoted,
+ * which avoids misparsing filenames that legitimately contain ` -> `, quote chars,
+ * or newlines. For R/C entries the two NUL-separated tokens are `DEST\0SRC`; we
+ * report DEST (the current working-tree path) and discard SRC.
+ */
+ @IpcMethod()
+ async getGitWorkingTreeFiles(dirPath: string): Promise<GitWorkingTreeFiles> {
+ const execFileAsync = promisify(execFile);
+ const added: string[] = [];
+ const modified: string[] = [];
+ const deleted: string[] = [];
+ try {
+ const { stdout } = await execFileAsync('git', ['status', '--porcelain', '-z'], {
+ cwd: dirPath,
+ timeout: 5000,
+ });
+ const tokens = stdout.split('\0');
+ let i = 0;
+ while (i < tokens.length) {
+ const entry = tokens[i];
+ i++;
+ if (entry.length < 3) continue;
+ const x = entry[0];
+ const y = entry[1];
+ const filePath = entry.slice(3);
+ // R/C entries carry an extra source-path token we must consume.
+ if (x === 'R' || x === 'C') i++;
+ if (!filePath) continue;
+ if (x === '?' && y === '?') {
+ added.push(filePath);
+ } else if (x === '!' && y === '!') {
+ // ignored — skip
+ } else if (x === 'D' || y === 'D') {
+ deleted.push(filePath);
+ } else if (x === 'A' || y === 'A') {
+ added.push(filePath);
+ } else {
+ modified.push(filePath);
+ }
+ }
+ return { added, deleted, modified };
+ } catch {
+ return { added: [], deleted: [], modified: [] };
+ }
+ }
+
+ /**
+ * 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).
+ */
+ @IpcMethod()
+ async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {
+ const execFileAsync = promisify(execFile);
+ try {
+ const { stdout: upstreamOut } = await execFileAsync(
+ 'git',
+ ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ const upstream = upstreamOut.trim();
+ if (!upstream) return { ahead: 0, behind: 0, hasUpstream: false };
+
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['rev-list', '--left-right', '--count', `${upstream}...HEAD`],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ 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 };
+ } catch {
+ // No upstream configured, detached HEAD, or git error — all treated as "no upstream"
+ return { ahead: 0, behind: 0, hasUpstream: false };
+ }
+ }
+
+ /**
+ * Check out (or create + check out) a branch.
+ * Relies on git itself to reject unsafe checkouts (dirty tree, non-fast-forward, etc.)
+ * and surfaces git's stderr so the UI can display a meaningful error.
+ */
+ @IpcMethod()
+ async checkoutGitBranch(payload: {
+ branch: string;
+ create?: boolean;
+ path: string;
+ }): Promise<GitCheckoutResult> {
+ const { path: dirPath, branch, create } = payload;
+ if (!branch?.trim()) {
+ return { error: 'Branch name is required', success: false };
+ }
+ // Reject obviously invalid refs early to avoid a confusing git error
+ if (/[\s~^:?*[\\]/.test(branch) || branch.startsWith('-') || branch.includes('..')) {
+ return { error: `Invalid branch name: ${branch}`, success: false };
+ }
+
+ const execFileAsync = promisify(execFile);
+ const args = create ? ['checkout', '-b', branch] : ['checkout', branch];
+ try {
+ await execFileAsync('git', args, { cwd: dirPath, timeout: 10_000 });
+ return { success: true };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ logger.debug('[checkoutGitBranch] failed', { args, stderr });
+ return { error: stderr || 'git checkout failed', success: false };
+ }
+ }
+}
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index 82b89d30dec..45fbac299d6 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -1,23 +1,12 @@
-import { execFile } from 'node:child_process';
-import { readFile } from 'node:fs/promises';
-import path from 'node:path';
import process from 'node:process';
-import { promisify } from 'node:util';
-
-import type {
- ElectronAppState,
- GitBranchInfo,
- GitBranchListItem,
- GitCheckoutResult,
- GitLinkedPullRequestResult,
- GitWorkingTreeStatus,
- ThemeMode,
-} from '@lobechat/electron-client-ipc';
+
+import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';
import { app, dialog, nativeTheme, shell } from 'electron';
import { macOS } from 'electron-is';
import { pathExists, readdir } from 'fs-extra';
import { legacyLocalDbDir } from '@/const/dir';
+import { detectRepoType } from '@/utils/git';
import { createLogger } from '@/utils/logger';
import {
getAccessibilityStatus,
@@ -195,7 +184,7 @@ export default class SystemController extends ControllerModule {
}
const folderPath = result.filePaths[0];
- const repoType = await this.detectRepoType(folderPath);
+ const repoType = await detectRepoType(folderPath);
return { path: folderPath, repoType };
}
@@ -245,265 +234,6 @@ export default class SystemController extends ControllerModule {
}
}
- @IpcMethod()
- async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {
- const commonDir = await this.resolveCommonGitDir(dirPath);
- if (!commonDir) return undefined;
- try {
- const config = await readFile(path.join(commonDir, 'config'), 'utf8');
- if (config.includes('github.com')) return 'github';
- return 'git';
- } catch {
- return undefined;
- }
- }
-
- /**
- * Read current git branch from `.git/HEAD`. Returns short sha on detached HEAD.
- * Handles both standard `.git` directories and `.git` worktree pointer files.
- */
- @IpcMethod()
- async getGitBranch(dirPath: string): Promise<GitBranchInfo> {
- try {
- const gitDir = await this.resolveGitDir(dirPath);
- if (!gitDir) return {};
-
- const head = (await readFile(path.join(gitDir, 'HEAD'), 'utf8')).trim();
- const refMatch = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
- if (refMatch) {
- return { branch: refMatch[1] };
- }
- // Detached HEAD — HEAD file contains the full sha
- if (/^[\da-f]{40}$/i.test(head)) {
- return { branch: head.slice(0, 7), detached: true };
- }
- return {};
- } catch {
- return {};
- }
- }
-
- /**
- * Query `gh` CLI for an open pull request whose head branch matches `branch`.
- * Returns status = 'gh-missing' when `gh` is not installed / not authenticated,
- * so the UI can render a helpful tooltip instead of an error.
- */
- @IpcMethod()
- async getLinkedPullRequest(payload: {
- branch: string;
- path: string;
- }): Promise<GitLinkedPullRequestResult> {
- const { path: dirPath, branch } = payload;
- if (!branch) {
- return { pullRequest: null, status: 'ok' };
- }
-
- const execFileAsync = promisify(execFile);
- try {
- const { stdout } = await execFileAsync(
- 'gh',
- [
- 'pr',
- 'list',
- '--head',
- branch,
- '--state',
- 'open',
- '--limit',
- '5',
- '--json',
- 'number,url,title,state',
- ],
- { cwd: dirPath, timeout: 8000 },
- );
- const parsed = JSON.parse(stdout.trim() || '[]') as Array<{
- number: number;
- state: string;
- title: string;
- url: string;
- }>;
- if (parsed.length === 0) {
- return { pullRequest: null, status: 'ok' };
- }
- const [primary, ...rest] = parsed;
- return {
- extraCount: rest.length,
- pullRequest: primary,
- status: 'ok',
- };
- } catch (error: any) {
- const code = error?.code;
- const stderr: string = error?.stderr ?? '';
- // `gh` binary not on PATH
- if (code === 'ENOENT') {
- return { pullRequest: null, status: 'gh-missing' };
- }
- // gh reports auth issues via stderr; treat as a soft-fail
- if (/auth\s+login|not\s+logged\s+in|authentication/i.test(stderr)) {
- return { pullRequest: null, status: 'gh-missing' };
- }
- logger.debug('[getLinkedPullRequest] failed', { branch, code, stderr });
- return { pullRequest: null, status: 'error' };
- }
- }
-
- /**
- * List local git branches ordered by most recent commit.
- * `current` is true for the checked-out branch.
- */
- @IpcMethod()
- async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {
- const execFileAsync = promisify(execFile);
- try {
- const { stdout } = await execFileAsync(
- 'git',
- [
- 'for-each-ref',
- '--sort=-committerdate',
- '--format=%(HEAD)%09%(refname:short)%09%(upstream:short)',
- 'refs/heads',
- ],
- { cwd: dirPath, timeout: 5000 },
- );
- return stdout
- .replaceAll('\r', '')
- .split('\n')
- .filter((line) => line.length > 0)
- .map((line) => {
- // Line format: "<HEAD-marker>\t<branch>\t<upstream>" where HEAD-marker is '*' or ' '
- const [head, name, upstream] = line.split('\t');
- return {
- current: head === '*',
- name: name ?? '',
- upstream: upstream || undefined,
- };
- })
- .filter((b) => b.name);
- } catch (error: any) {
- logger.warn('[listGitBranches] git command failed', {
- code: error?.code,
- cwd: dirPath,
- message: error?.message,
- stderr: error?.stderr?.toString?.() ?? error?.stderr,
- });
- return [];
- }
- }
-
- /**
- * Bucket dirty files into added / modified / deleted via `git status --porcelain`.
- * Each file is counted once: untracked (`??`) and staged-add (`A`) → added,
- * any `D` in index or working tree → deleted, everything else (`M`/`R`/`C`/`T`/`U`) → modified.
- */
- @IpcMethod()
- async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
- const execFileAsync = promisify(execFile);
- try {
- const { stdout } = await execFileAsync('git', ['status', '--porcelain'], {
- cwd: dirPath,
- timeout: 5000,
- });
- let added = 0;
- let modified = 0;
- let deleted = 0;
- for (const line of stdout.split('\n')) {
- if (line.length < 2) continue;
- const x = line[0];
- const y = line[1];
- if (x === '?' && y === '?') {
- added++;
- } else if (x === '!' && y === '!') {
- // ignored — skip
- } else if (x === 'D' || y === 'D') {
- deleted++;
- } else if (x === 'A' || y === 'A') {
- added++;
- } else {
- modified++;
- }
- }
- const total = added + modified + deleted;
- return { added, clean: total === 0, deleted, modified, total };
- } catch {
- return { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
- }
- }
-
- /**
- * Check out (or create + check out) a branch.
- * Relies on git itself to reject unsafe checkouts (dirty tree, non-fast-forward, etc.)
- * and surfaces git's stderr so the UI can display a meaningful error.
- */
- @IpcMethod()
- async checkoutGitBranch(payload: {
- branch: string;
- create?: boolean;
- path: string;
- }): Promise<GitCheckoutResult> {
- const { path: dirPath, branch, create } = payload;
- if (!branch?.trim()) {
- return { error: 'Branch name is required', success: false };
- }
- // Reject obviously invalid refs early to avoid a confusing git error
- if (/[\s~^:?*[\\]/.test(branch) || branch.startsWith('-') || branch.includes('..')) {
- return { error: `Invalid branch name: ${branch}`, success: false };
- }
-
- const execFileAsync = promisify(execFile);
- const args = create ? ['checkout', '-b', branch] : ['checkout', branch];
- try {
- await execFileAsync('git', args, { cwd: dirPath, timeout: 10_000 });
- return { success: true };
- } catch (error: any) {
- const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
- logger.debug('[checkoutGitBranch] failed', { args, stderr });
- return { error: stderr || 'git checkout failed', success: false };
- }
- }
-
- /**
- * Resolve the common git dir — where shared state like `config` and
- * `packed-refs` lives. For linked worktrees, `resolveGitDir` returns
- * `.git/worktrees/<name>/` which has its own `HEAD` but no `config`;
- * the `commondir` pointer inside it resolves to the main repo's gitdir.
- */
- private async resolveCommonGitDir(dirPath: string): Promise<string | undefined> {
- const gitDir = await this.resolveGitDir(dirPath);
- if (!gitDir) return undefined;
- try {
- const commondir = (await readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();
- if (!commondir) return gitDir;
- return path.isAbsolute(commondir) ? commondir : path.resolve(gitDir, commondir);
- } catch {
- return gitDir;
- }
- }
-
- /**
- * Resolve the actual `.git` directory for a working tree.
- * Supports both standard layouts and worktree pointer files (`.git` as a regular file).
- */
- private async resolveGitDir(dirPath: string): Promise<string | undefined> {
- const gitPath = path.join(dirPath, '.git');
- try {
- const content = await readFile(gitPath, 'utf8');
- const worktreeMatch = /^gitdir:\s*(\S.*)$/m.exec(content.trim());
- if (worktreeMatch) {
- const resolved = worktreeMatch[1].trim();
- return path.isAbsolute(resolved) ? resolved : path.resolve(dirPath, resolved);
- }
- } catch {
- // `.git` is a directory (EISDIR) or missing — fall through
- }
- try {
- const stat = await readdir(gitPath);
- if (stat.length > 0) return gitPath;
- } catch {
- return undefined;
- }
- return undefined;
- }
-
private async setSystemThemeMode(themeMode: ThemeMode) {
nativeTheme.themeSource = themeMode;
}
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index 32eb70f7850..faf7575e2c9 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -5,6 +5,7 @@ import BrowserWindowsCtr from './BrowserWindowsCtr';
import CliCtr from './CliCtr';
import DevtoolsCtr from './DevtoolsCtr';
import GatewayConnectionCtr from './GatewayConnectionCtr';
+import GitCtr from './GitCtr';
import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
import LocalFileCtr from './LocalFileCtr';
import McpCtr from './McpCtr';
@@ -29,6 +30,7 @@ export const controllerIpcConstructors = [
CliCtr,
DevtoolsCtr,
GatewayConnectionCtr,
+ GitCtr,
LocalFileCtr,
McpCtr,
McpInstallCtr,
diff --git a/apps/desktop/src/main/utils/__tests__/git.test.ts b/apps/desktop/src/main/utils/__tests__/git.test.ts
new file mode 100644
index 00000000000..17f866967cd
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/git.test.ts
@@ -0,0 +1,65 @@
+import { readFile } from 'node:fs/promises';
+
+import { readdir } from 'fs-extra';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { detectRepoType } from '../git';
+
+vi.mock('node:fs/promises', () => ({
+ readFile: vi.fn(),
+}));
+
+vi.mock('fs-extra', () => ({
+ readdir: vi.fn(),
+}));
+
+const eisdir = () => Object.assign(new Error('EISDIR'), { code: 'EISDIR' });
+const enoent = () => Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+
+// Stub a flat (non-worktree) git repo at /repo whose config is `config`.
+const stubRepo = (config: string) => {
+ vi.mocked(readFile).mockImplementation(async (filePath) => {
+ const p = String(filePath);
+ if (p.endsWith('/.git')) throw eisdir(); // .git is a directory
+ if (p.endsWith('/commondir')) throw enoent(); // no commondir → use gitDir
+ if (p.endsWith('/config')) return config;
+ throw new Error(`unexpected readFile: ${p}`);
+ });
+ vi.mocked(readdir).mockResolvedValue(['HEAD', 'config'] as any);
+};
+
+describe('detectRepoType', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each([
+ ['SCP-like SSH', '[remote "origin"]\n\turl = [email protected]:owner/repo.git\n'],
+ ['HTTPS', '[remote "origin"]\n\turl = https://github.com/owner/repo.git\n'],
+ ['ssh:// scheme', '[remote "origin"]\n\turl = ssh://[email protected]/owner/repo.git\n'],
+ ['git:// scheme', '[remote "origin"]\n\turl = git://github.com/owner/repo.git\n'],
+ ])('classifies %s remote as github', async (_label, config) => {
+ stubRepo(config);
+ await expect(detectRepoType('/repo')).resolves.toBe('github');
+ });
+
+ it.each([
+ ['look-alike host', '[remote "origin"]\n\turl = [email protected]:owner/repo.git\n'],
+ ['suffix injection', '[remote "origin"]\n\turl = https://github.com.attacker.com/x.git\n'],
+ [
+ 'github.com inside path of unrelated host',
+ '[remote "origin"]\n\turl = https://attacker.com/?ref=github.com/x\n',
+ ],
+ ['GitHub Enterprise', '[remote "origin"]\n\turl = [email protected]:owner/repo.git\n'],
+ ['no remote at all', '[core]\n\trepositoryformatversion = 0\n'],
+ ])('does not misclassify %s as github', async (_label, config) => {
+ stubRepo(config);
+ await expect(detectRepoType('/repo')).resolves.toBe('git');
+ });
+
+ it('returns undefined when there is no .git', async () => {
+ vi.mocked(readFile).mockRejectedValue(enoent());
+ vi.mocked(readdir).mockRejectedValue(enoent());
+ await expect(detectRepoType('/not-a-repo')).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/utils/git.ts b/apps/desktop/src/main/utils/git.ts
new file mode 100644
index 00000000000..3b6543a599f
--- /dev/null
+++ b/apps/desktop/src/main/utils/git.ts
@@ -0,0 +1,71 @@
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { readdir } from 'fs-extra';
+
+/**
+ * Resolve the actual `.git` directory for a working tree.
+ * Supports both standard layouts and worktree pointer files (`.git` as a regular file
+ * containing `gitdir: <path>`).
+ */
+export const resolveGitDir = async (dirPath: string): Promise<string | undefined> => {
+ const gitPath = path.join(dirPath, '.git');
+ try {
+ const content = await readFile(gitPath, 'utf8');
+ const worktreeMatch = /^gitdir:\s*(\S.*)$/m.exec(content.trim());
+ if (worktreeMatch) {
+ const resolved = worktreeMatch[1].trim();
+ return path.isAbsolute(resolved) ? resolved : path.resolve(dirPath, resolved);
+ }
+ } catch {
+ // `.git` is a directory (EISDIR) or missing — fall through
+ }
+ try {
+ const stat = await readdir(gitPath);
+ if (stat.length > 0) return gitPath;
+ } catch {
+ return undefined;
+ }
+ return undefined;
+};
+
+/**
+ * Resolve the common git dir — where shared state like `config` and
+ * `packed-refs` lives. For linked worktrees, `resolveGitDir` returns
+ * `.git/worktrees/<name>/` which has its own `HEAD` but no `config`;
+ * the `commondir` pointer inside it resolves to the main repo's gitdir.
+ */
+export const resolveCommonGitDir = async (dirPath: string): Promise<string | undefined> => {
+ const gitDir = await resolveGitDir(dirPath);
+ if (!gitDir) return undefined;
+ try {
+ const commondir = (await readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();
+ if (!commondir) return gitDir;
+ return path.isAbsolute(commondir) ? commondir : path.resolve(gitDir, commondir);
+ } catch {
+ return gitDir;
+ }
+};
+
+// Match `github.com` only in a remote-URL host position: preceded by `@`, `/`,
+// or line start (covers `[email protected]:`, `https://github.com/`,
+// `ssh://[email protected]/`, etc.) and followed by `:` or `/`. Avoids matching
+// look-alikes like `evilgithub.com` or `github.com.attacker.com`.
+const GITHUB_REMOTE_HOST_RE = /(?:^|[@/])github\.com[:/]/m;
+
+/**
+ * Classify a working tree as `git` (plain) / `github` (origin points at github.com) /
+ * `undefined` (not a git repo). Reads the shared gitdir's `config` so submodules and
+ * linked worktrees resolve the same as the main repo.
+ */
+export const detectRepoType = async (dirPath: string): Promise<'git' | 'github' | undefined> => {
+ const commonDir = await resolveCommonGitDir(dirPath);
+ if (!commonDir) return undefined;
+ try {
+ const config = await readFile(path.join(commonDir, 'config'), 'utf8');
+ if (GITHUB_REMOTE_HOST_RE.test(config)) return 'github';
+ return 'git';
+ } catch {
+ return undefined;
+ }
+};
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 8fe9e3cc1a6..d37d95e4ca0 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -435,6 +435,9 @@
"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",
@@ -448,6 +451,11 @@
"localSystem.workingDirectory.current": "Current working directory",
"localSystem.workingDirectory.detachedHead": "Detached HEAD at {{sha}}",
"localSystem.workingDirectory.diffStatTooltip": "Added {{added}} · Modified {{modified}} · Deleted {{deleted}}",
+ "localSystem.workingDirectory.filesAdded": "Added",
+ "localSystem.workingDirectory.filesDeleted": "Deleted",
+ "localSystem.workingDirectory.filesEmpty": "No uncommitted changes",
+ "localSystem.workingDirectory.filesLoading": "Loading changes…",
+ "localSystem.workingDirectory.filesModified": "Modified",
"localSystem.workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests",
"localSystem.workingDirectory.newBranchPlaceholder": "feature/new-branch-name",
"localSystem.workingDirectory.noRecent": "No recent directories",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 9ce552367e5..2e7265263de 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -435,6 +435,9 @@
"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": "分支",
@@ -448,6 +451,11 @@
"localSystem.workingDirectory.current": "当前工作目录",
"localSystem.workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}",
"localSystem.workingDirectory.diffStatTooltip": "新增 {{added}} · 修改 {{modified}} · 删除 {{deleted}}",
+ "localSystem.workingDirectory.filesAdded": "新增",
+ "localSystem.workingDirectory.filesDeleted": "删除",
+ "localSystem.workingDirectory.filesEmpty": "没有未提交的变更",
+ "localSystem.workingDirectory.filesLoading": "加载中…",
+ "localSystem.workingDirectory.filesModified": "修改",
"localSystem.workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",
"localSystem.workingDirectory.newBranchPlaceholder": "feature/新分支名称",
"localSystem.workingDirectory.noRecent": "暂无最近目录",
diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.ts
index 997d36b23c8..3dc859dfc6f 100644
--- a/packages/electron-client-ipc/src/types/system.ts
+++ b/packages/electron-client-ipc/src/types/system.ts
@@ -69,7 +69,27 @@ export interface GitWorkingTreeStatus {
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/BranchSwitcher.tsx b/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsx
index 56bea4e6704..09aed12be00 100644
--- a/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsx
+++ b/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsx
@@ -22,7 +22,7 @@ import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import { message } from '@/components/AntdStaticMethods';
-import { electronSystemService } from '@/services/electron/system';
+import { electronGitService } from '@/services/electron/git';
import { useWorkingTreeStatus } from './useWorkingTreeStatus';
@@ -175,7 +175,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
mutate: mutateBranches,
} = useSWR(
open ? ['git-branches', path] : null,
- () => electronSystemService.listGitBranches(path),
+ () => electronGitService.listGitBranches(path),
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
const { data: workingStatus, mutate: mutateWorkingStatus } = useWorkingTreeStatus(path);
@@ -224,7 +224,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
}
setBusyBranch(branch);
try {
- const result = await electronSystemService.checkoutGitBranch({
+ const result = await electronGitService.checkoutGitBranch({
branch,
create,
path,
diff --git a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
index 1d8424cb60d..966a901dd37 100644
--- a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
+++ b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx
@@ -1,16 +1,34 @@
-import { Icon, Tooltip } from '@lobehub/ui';
+import { Icon, Popover, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { GitBranchIcon, GitPullRequest } from 'lucide-react';
+import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { electronSystemService } from '@/services/electron/system';
import BranchSwitcher from './BranchSwitcher';
+import { useGitAheadBehind } from './useGitAheadBehind';
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;
@@ -23,10 +41,7 @@ const styles = createStaticStyles(({ css }) => ({
gap: 4px;
align-items: center;
- margin-inline-start: 2px;
-
font-variant-numeric: tabular-nums;
- line-height: 1;
`,
diffStatAdded: css`
color: ${cssVar.colorSuccess};
@@ -94,7 +109,9 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
const { t } = useTranslation('plugin');
const { data, mutate } = useGitInfo(path, isGithub);
const { data: workingStatus, mutate: mutateWorkingStatus } = useWorkingTreeStatus(path);
+ const { data: aheadBehind, mutate: mutateAheadBehind } = useGitAheadBehind(path);
const [switcherOpen, setSwitcherOpen] = useState(false);
+ const [filesOpen, setFilesOpen] = useState(false);
const handleOpenPr = useCallback(() => {
if (data?.pullRequest?.url) {
@@ -119,67 +136,122 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {
? t('localSystem.workingDirectory.ghMissing')
: undefined;
- const diffStat =
- workingStatus && !workingStatus.clean ? (
- <span className={styles.diffStat}>
- {workingStatus.added > 0 && (
- <span className={styles.diffStatAdded}>+{workingStatus.added}</span>
- )}
- {workingStatus.modified > 0 && (
- <span className={styles.diffStatModified}>±{workingStatus.modified}</span>
- )}
- {workingStatus.deleted > 0 && (
- <span className={styles.diffStatDeleted}>-{workingStatus.deleted}</span>
- )}
- </span>
- ) : null;
-
- const diffStatTooltip =
- workingStatus && !workingStatus.clean
- ? t('localSystem.workingDirectory.diffStatTooltip', {
- added: workingStatus.added,
- deleted: workingStatus.deleted,
- modified: workingStatus.modified,
+ const hasChanges = !!workingStatus && !workingStatus.clean;
+
+ const diffStatTooltip = hasChanges
+ ? t('localSystem.workingDirectory.diffStatTooltip', {
+ added: workingStatus!.added,
+ deleted: workingStatus!.deleted,
+ modified: workingStatus!.modified,
+ })
+ : undefined;
+
+ 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,
})
- : undefined;
+ : 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 branchTrigger = (
<div className={styles.trigger}>
<Icon icon={GitBranchIcon} size={12} />
<span className={styles.branchLabel}>{data.branch}</span>
- {diffStat}
+ {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 wrappedBranchTrigger =
- diffStat && diffStatTooltip ? (
- <Tooltip title={diffStatTooltip}>{branchTrigger}</Tooltip>
- ) : (
- branchTrigger
+ const branchNode = data.detached ? (
+ <Tooltip title={combinedBranchTooltip}>{branchTrigger}</Tooltip>
+ ) : (
+ <BranchSwitcher
+ currentBranch={data.branch}
+ open={switcherOpen}
+ path={path}
+ onOpenChange={setSwitcherOpen}
+ onAfterCheckout={() => {
+ void mutate();
+ void mutateWorkingStatus();
+ void mutateAheadBehind();
+ }}
+ onExternalRefresh={async () => {
+ await Promise.all([mutate(), mutateWorkingStatus(), mutateAheadBehind()]);
+ }}
+ >
+ <Tooltip title={combinedBranchTooltip}>{branchTrigger}</Tooltip>
+ </BranchSwitcher>
+ );
+
+ const diffNode = (() => {
+ if (!hasChanges || !workingStatus) return null;
+ const diffButton = (
+ <div className={styles.trigger} role="button">
+ <span className={styles.diffStat}>
+ {workingStatus.added > 0 && (
+ <span className={styles.diffStatAdded}>+{workingStatus.added}</span>
+ )}
+ {workingStatus.modified > 0 && (
+ <span className={styles.diffStatModified}>±{workingStatus.modified}</span>
+ )}
+ {workingStatus.deleted > 0 && (
+ <span className={styles.diffStatDeleted}>-{workingStatus.deleted}</span>
+ )}
+ </span>
+ </div>
);
+ return (
+ <Popover
+ arrow={false}
+ content={<WorkingTreeFilesContent enabled={filesOpen} path={path} />}
+ open={filesOpen}
+ placement="bottomLeft"
+ styles={{ content: { padding: 0 } }}
+ trigger="click"
+ onOpenChange={setFilesOpen}
+ >
+ <div>
+ {filesOpen ? diffButton : <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>}
+ </div>
+ </Popover>
+ );
+ })();
return (
<>
<div className={styles.separator} />
- {data.detached ? (
- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
- ) : (
- <BranchSwitcher
- currentBranch={data.branch}
- open={switcherOpen}
- path={path}
- onOpenChange={setSwitcherOpen}
- onAfterCheckout={() => {
- void mutate();
- void mutateWorkingStatus();
- }}
- onExternalRefresh={async () => {
- await Promise.all([mutate(), mutateWorkingStatus()]);
- }}
- >
- {wrappedBranchTrigger}
- </BranchSwitcher>
- )}
+ {branchNode}
+ {diffNode}
{data.pullRequest && (
<>
<div className={styles.separator} />
diff --git a/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsx b/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsx
new file mode 100644
index 00000000000..f53a0fc65a0
--- /dev/null
+++ b/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsx
@@ -0,0 +1,151 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkingTreeFiles } from './useWorkingTreeFiles';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ overflow-y: auto;
+
+ width: 320px;
+ max-height: 360px;
+ padding: 4px;
+
+ font-size: 12px;
+ `,
+ empty: css`
+ padding-block: 16px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ path: css`
+ overflow: hidden;
+ flex: 1;
+
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ row: css`
+ display: flex;
+ gap: 12px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-radius: 4px;
+
+ line-height: 1.4;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ sectionHeader: css`
+ padding-block: 6px 4px;
+ padding-inline: 12px;
+
+ font-size: 11px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ text-transform: uppercase;
+ `,
+ statusAdded: css`
+ flex: none;
+ width: 10px;
+ color: ${cssVar.colorSuccess};
+ text-align: center;
+ `,
+ statusDeleted: css`
+ flex: none;
+ width: 10px;
+ color: ${cssVar.colorError};
+ text-align: center;
+ `,
+ statusModified: css`
+ flex: none;
+ width: 10px;
+ color: ${cssVar.colorWarning};
+ text-align: center;
+ `,
+}));
+
+interface WorkingTreeFilesContentProps {
+ enabled: boolean;
+ path: string;
+}
+
+const WorkingTreeFilesContent = memo<WorkingTreeFilesContentProps>(({ path, enabled }) => {
+ const { t } = useTranslation('plugin');
+ const { data, isLoading } = useWorkingTreeFiles(path, enabled);
+
+ const sections = useMemo(
+ () => [
+ {
+ items: data?.added ?? [],
+ key: 'added' as const,
+ label: t('localSystem.workingDirectory.filesAdded'),
+ sign: '+',
+ statusClass: styles.statusAdded,
+ },
+ {
+ items: data?.modified ?? [],
+ key: 'modified' as const,
+ label: t('localSystem.workingDirectory.filesModified'),
+ sign: '±',
+ statusClass: styles.statusModified,
+ },
+ {
+ items: data?.deleted ?? [],
+ key: 'deleted' as const,
+ label: t('localSystem.workingDirectory.filesDeleted'),
+ sign: '−',
+ statusClass: styles.statusDeleted,
+ },
+ ],
+ [data, t],
+ );
+
+ const hasAny = sections.some((s) => s.items.length > 0);
+
+ if (!data && isLoading) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.empty}>{t('localSystem.workingDirectory.filesLoading')}</div>
+ </div>
+ );
+ }
+
+ if (!hasAny) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.empty}>{t('localSystem.workingDirectory.filesEmpty')}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.container}>
+ {sections.map(({ key, items, label, sign, statusClass }) =>
+ items.length > 0 ? (
+ <div key={key}>
+ <div className={styles.sectionHeader}>
+ {label} · {items.length}
+ </div>
+ {items.map((file) => (
+ <div className={styles.row} key={`${key}:${file}`} title={file}>
+ <span className={statusClass}>{sign}</span>
+ <span className={styles.path}>{file}</span>
+ </div>
+ ))}
+ </div>
+ ) : null,
+ )}
+ </div>
+ );
+});
+
+WorkingTreeFilesContent.displayName = 'WorkingTreeFilesContent';
+
+export default WorkingTreeFilesContent;
diff --git a/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts b/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts
new file mode 100644
index 00000000000..0ab31677154
--- /dev/null
+++ b/src/features/ChatInput/RuntimeConfig/useGitAheadBehind.ts
@@ -0,0 +1,20 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useClientDataSWR } from '@/libs/swr';
+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.
+ */
+export const useGitAheadBehind = (dirPath?: string) => {
+ const key = isDesktop && dirPath ? ['git-ahead-behind', dirPath] : null;
+
+ return useClientDataSWR(key, () => electronGitService.getGitAheadBehind(dirPath!), {
+ focusThrottleInterval: 5 * 1000,
+ revalidateOnFocus: true,
+ shouldRetryOnError: false,
+ });
+};
diff --git a/src/features/ChatInput/RuntimeConfig/useGitInfo.ts b/src/features/ChatInput/RuntimeConfig/useGitInfo.ts
index 5eabb6303e4..8dc32698823 100644
--- a/src/features/ChatInput/RuntimeConfig/useGitInfo.ts
+++ b/src/features/ChatInput/RuntimeConfig/useGitInfo.ts
@@ -2,7 +2,7 @@ import { isDesktop } from '@lobechat/const';
import type { GitLinkedPullRequest } from '@lobechat/electron-client-ipc';
import { useClientDataSWR } from '@/libs/swr';
-import { electronSystemService } from '@/services/electron/system';
+import { electronGitService } from '@/services/electron/git';
export interface GitInfo {
branch?: string;
@@ -13,13 +13,13 @@ export interface GitInfo {
}
const fetchGitInfo = async (dirPath: string, isGithub: boolean): Promise<GitInfo> => {
- const { branch, detached } = await electronSystemService.getGitBranch(dirPath);
+ const { branch, detached } = await electronGitService.getGitBranch(dirPath);
if (!branch) return {};
// Skip PR lookup for detached HEAD or non-github repos
if (detached || !isGithub) return { branch, detached };
- const prResult = await electronSystemService.getLinkedPullRequest({ branch, path: dirPath });
+ const prResult = await electronGitService.getLinkedPullRequest({ branch, path: dirPath });
return {
branch,
detached,
diff --git a/src/features/ChatInput/RuntimeConfig/useRepoType.ts b/src/features/ChatInput/RuntimeConfig/useRepoType.ts
index 96c1a628e00..b3c15f73642 100644
--- a/src/features/ChatInput/RuntimeConfig/useRepoType.ts
+++ b/src/features/ChatInput/RuntimeConfig/useRepoType.ts
@@ -2,7 +2,7 @@ import { isDesktop } from '@lobechat/const';
import { useEffect, useMemo } from 'react';
import useSWR from 'swr';
-import { electronSystemService } from '@/services/electron/system';
+import { electronGitService } from '@/services/electron/git';
import { getRecentDirs, setRecentDirRepoType } from './recentDirs';
@@ -26,7 +26,7 @@ export const useRepoType = (path?: string): RepoType => {
const { data: probed } = useSWR(
shouldProbe ? ['detect-repo-type', path] : null,
- () => electronSystemService.detectRepoType(path!),
+ () => electronGitService.detectRepoType(path!),
{
dedupingInterval: 60 * 1000,
revalidateOnFocus: false,
diff --git a/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.ts b/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.ts
new file mode 100644
index 00000000000..e90b0d294b9
--- /dev/null
+++ b/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.ts
@@ -0,0 +1,19 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { electronGitService } from '@/services/electron/git';
+
+/**
+ * Per-file breakdown of the working tree (paths grouped by add/modify/delete).
+ * Lazy — only fetched when `enabled` is true (e.g. the popover is open), since
+ * it's strictly richer than useWorkingTreeStatus and most users never open the list.
+ */
+export const useWorkingTreeFiles = (dirPath?: string, enabled?: boolean) => {
+ const key = isDesktop && dirPath && enabled ? ['git-working-tree-files', dirPath] : null;
+
+ return useClientDataSWR(key, () => electronGitService.getGitWorkingTreeFiles(dirPath!), {
+ focusThrottleInterval: 5 * 1000,
+ revalidateOnFocus: true,
+ shouldRetryOnError: false,
+ });
+};
diff --git a/src/features/ChatInput/RuntimeConfig/useWorkingTreeStatus.ts b/src/features/ChatInput/RuntimeConfig/useWorkingTreeStatus.ts
index c0a850f7bed..7e807edbc7e 100644
--- a/src/features/ChatInput/RuntimeConfig/useWorkingTreeStatus.ts
+++ b/src/features/ChatInput/RuntimeConfig/useWorkingTreeStatus.ts
@@ -1,7 +1,7 @@
import { isDesktop } from '@lobechat/const';
import { useClientDataSWR } from '@/libs/swr';
-import { electronSystemService } from '@/services/electron/system';
+import { electronGitService } from '@/services/electron/git';
/**
* Working-tree dirty-file breakdown for the current cwd.
@@ -12,7 +12,7 @@ import { electronSystemService } from '@/services/electron/system';
export const useWorkingTreeStatus = (dirPath?: string) => {
const key = isDesktop && dirPath ? ['git-working-tree-status', dirPath] : null;
- return useClientDataSWR(key, () => electronSystemService.getGitWorkingTreeStatus(dirPath!), {
+ return useClientDataSWR(key, () => electronGitService.getGitWorkingTreeStatus(dirPath!), {
focusThrottleInterval: 5 * 1000,
revalidateOnFocus: true,
shouldRetryOnError: false,
diff --git a/src/features/Conversation/TodoProgress/index.tsx b/src/features/Conversation/TodoProgress/index.tsx
index 9afeff2be16..0036abc35bb 100644
--- a/src/features/Conversation/TodoProgress/index.tsx
+++ b/src/features/Conversation/TodoProgress/index.tsx
@@ -3,16 +3,21 @@
import { type StepContextTodos } from '@lobechat/types';
import { Checkbox, Flexbox, Icon, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { ChevronDown, ChevronUp, CircleArrowRight, ListTodo } from 'lucide-react';
+import { ChevronDown, ChevronUp, CircleArrowRight } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { selectTodosFromMessages } from '@/store/chat/slices/message/selectors/dbMessage';
+import { selectCurrentTurnTodosFromMessages } from '@/store/chat/slices/message/selectors/dbMessage';
import { shinyTextStyles } from '@/styles';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';
+const RING_SIZE = 14;
+const RING_STROKE = 2;
+const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;
+const RING_CIRCUM = 2 * Math.PI * RING_RADIUS;
+
const styles = createStaticStyles(({ css, cssVar }) => ({
collapsed: css`
max-height: 0;
@@ -80,17 +85,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
gap: 6px;
align-items: center;
`,
- progress: css`
- flex: 1;
- height: 4px;
- border-radius: 2px;
- background: ${cssVar.colorFillSecondary};
+ ring: css`
+ transform: rotate(-90deg);
+ flex-shrink: 0;
+ `,
+ ringProgress: css`
+ transition:
+ stroke-dashoffset 240ms ease,
+ stroke 240ms ease;
`,
- progressFill: css`
- height: 100%;
- border-radius: 2px;
- background: ${cssVar.colorSuccess};
- transition: width 0.3s ${cssVar.motionEaseInOut};
+ ringTrack: css`
+ stroke: ${cssVar.colorFillSecondary};
`,
textCompleted: css`
color: ${cssVar.colorTextQuaternary};
@@ -116,9 +121,11 @@ const TodoProgress = memo<TodoProgressProps>(({ className }) => {
const dbMessages = useConversationStore(dataSelectors.dbMessages);
const isAIGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
- // Extract todos from messages
+ // Extract todos produced within the current agent turn (after the last user
+ // message). Older turns' todos intentionally drop out so a new operation
+ // doesn't keep a stale completed progress bar on screen.
const todos: StepContextTodos | undefined = useMemo(
- () => selectTodosFromMessages(dbMessages),
+ () => selectCurrentTurnTodosFromMessages(dbMessages),
[dbMessages],
);
@@ -136,6 +143,10 @@ const TodoProgress = memo<TodoProgressProps>(({ className }) => {
// Don't render if no todos
if (total === 0) return null;
+ const allDone = completed === total;
+ const ringColor = allDone ? cssVar.colorSuccess : cssVar.colorInfo;
+ const ringOffset = RING_CIRCUM * (1 - progressPercent / 100);
+
const toggleExpanded = () => setExpanded(!expanded);
return (
@@ -144,7 +155,28 @@ const TodoProgress = memo<TodoProgressProps>(({ className }) => {
{/* Header */}
<Flexbox horizontal align="center" gap={8} justify="space-between">
<Flexbox horizontal align="center" gap={8} style={{ flex: 1, minWidth: 0 }}>
- <Icon icon={ListTodo} size={16} style={{ color: cssVar.colorPrimary, flexShrink: 0 }} />
+ <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>
+ <circle
+ className={styles.ringTrack}
+ cx={RING_SIZE / 2}
+ cy={RING_SIZE / 2}
+ fill="none"
+ r={RING_RADIUS}
+ strokeWidth={RING_STROKE}
+ />
+ <circle
+ className={styles.ringProgress}
+ cx={RING_SIZE / 2}
+ cy={RING_SIZE / 2}
+ fill="none"
+ r={RING_RADIUS}
+ stroke={ringColor}
+ strokeDasharray={RING_CIRCUM}
+ strokeDashoffset={ringOffset}
+ strokeLinecap="round"
+ strokeWidth={RING_STROKE}
+ />
+ </svg>
<span className={cx(styles.header, isAIGenerating && shinyTextStyles.shinyText)}>
{currentPendingTask?.text ||
t('todoProgress.allCompleted', { defaultValue: 'All tasks completed' })}
@@ -162,13 +194,6 @@ const TodoProgress = memo<TodoProgressProps>(({ className }) => {
/>
</Flexbox>
- {/* Progress Bar */}
- <Flexbox horizontal gap={8} style={{ marginTop: 8 }}>
- <div className={styles.progress}>
- <div className={styles.progressFill} style={{ width: `${progressPercent}%` }} />
- </div>
- </Flexbox>
-
{/* Expandable Todo List */}
<div className={cx(styles.listContainer, expanded ? styles.expanded : styles.collapsed)}>
{items.map((item, index) => {
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index e016775acb9..721a0b10b4e 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -453,9 +453,18 @@ 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.detachedHead': 'Detached HEAD at {{sha}}',
'localSystem.workingDirectory.diffStatTooltip':
'Added {{added}} · Modified {{modified}} · Deleted {{deleted}}',
+ 'localSystem.workingDirectory.filesAdded': 'Added',
+ 'localSystem.workingDirectory.filesDeleted': 'Deleted',
+ 'localSystem.workingDirectory.filesEmpty': 'No uncommitted changes',
+ 'localSystem.workingDirectory.filesLoading': 'Loading changes…',
+ 'localSystem.workingDirectory.filesModified': 'Modified',
'localSystem.workingDirectory.ghMissing':
'Install and log in to the GitHub CLI (`gh`) to see linked pull requests',
'localSystem.workingDirectory.newBranchPlaceholder': 'feature/new-branch-name',
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
new file mode 100644
index 00000000000..24f285f803d
--- /dev/null
+++ b/src/services/electron/git.ts
@@ -0,0 +1,63 @@
+import {
+ type GitAheadBehind,
+ type GitBranchInfo,
+ type GitBranchListItem,
+ type GitCheckoutResult,
+ type GitLinkedPullRequestResult,
+ type GitWorkingTreeFiles,
+ type GitWorkingTreeStatus,
+} from '@lobechat/electron-client-ipc';
+
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+/**
+ * Renderer-side wrapper for the `git.*` IPC group exposed by GitController.
+ * Kept separate from ElectronSystemService so that git concerns don't leak
+ * back into the system/windows/menu surface.
+ */
+class ElectronGitService {
+ private get ipc() {
+ return ensureElectronIpc();
+ }
+
+ async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {
+ return this.ipc.git.detectRepoType(dirPath);
+ }
+
+ async getGitBranch(dirPath: string): Promise<GitBranchInfo> {
+ return this.ipc.git.getGitBranch(dirPath);
+ }
+
+ async getLinkedPullRequest(params: {
+ branch: string;
+ path: string;
+ }): Promise<GitLinkedPullRequestResult> {
+ return this.ipc.git.getLinkedPullRequest(params);
+ }
+
+ async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {
+ return this.ipc.git.listGitBranches(dirPath);
+ }
+
+ async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
+ return this.ipc.git.getGitWorkingTreeStatus(dirPath);
+ }
+
+ async getGitWorkingTreeFiles(dirPath: string): Promise<GitWorkingTreeFiles> {
+ return this.ipc.git.getGitWorkingTreeFiles(dirPath);
+ }
+
+ async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {
+ return this.ipc.git.getGitAheadBehind(dirPath);
+ }
+
+ async checkoutGitBranch(params: {
+ branch: string;
+ create?: boolean;
+ path: string;
+ }): Promise<GitCheckoutResult> {
+ return this.ipc.git.checkoutGitBranch(params);
+ }
+}
+
+export const electronGitService = new ElectronGitService();
diff --git a/src/services/electron/system.ts b/src/services/electron/system.ts
index dd84bfcb514..4bbcbb74f4d 100644
--- a/src/services/electron/system.ts
+++ b/src/services/electron/system.ts
@@ -1,10 +1,5 @@
import {
type ElectronAppState,
- type GitBranchInfo,
- type GitBranchListItem,
- type GitCheckoutResult,
- type GitLinkedPullRequestResult,
- type GitWorkingTreeStatus,
type WindowMinimumSizeParams,
type WindowSizeParams,
} from '@lobechat/electron-client-ipc';
@@ -86,37 +81,6 @@ class ElectronSystemService {
}): Promise<{ path: string; repoType?: 'git' | 'github' } | undefined> {
return this.ipc.system.selectFolder(params);
}
-
- async getGitBranch(dirPath: string): Promise<GitBranchInfo> {
- return this.ipc.system.getGitBranch(dirPath);
- }
-
- async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {
- return this.ipc.system.detectRepoType(dirPath);
- }
-
- async getLinkedPullRequest(params: {
- branch: string;
- path: string;
- }): Promise<GitLinkedPullRequestResult> {
- return this.ipc.system.getLinkedPullRequest(params);
- }
-
- async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {
- return this.ipc.system.listGitBranches(dirPath);
- }
-
- async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
- return this.ipc.system.getGitWorkingTreeStatus(dirPath);
- }
-
- async checkoutGitBranch(params: {
- branch: string;
- create?: boolean;
- path: string;
- }): Promise<GitCheckoutResult> {
- return this.ipc.system.checkoutGitBranch(params);
- }
}
// Export a singleton instance of the service
diff --git a/src/store/chat/slices/message/selectors/dbMessage.test.ts b/src/store/chat/slices/message/selectors/dbMessage.test.ts
index 818747f84ca..1049cd35504 100644
--- a/src/store/chat/slices/message/selectors/dbMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/dbMessage.test.ts
@@ -1,7 +1,7 @@
import { type UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { selectTodosFromMessages } from './dbMessage';
+import { selectCurrentTurnTodosFromMessages, selectTodosFromMessages } from './dbMessage';
describe('selectTodosFromMessages', () => {
const createGTDToolMessage = (todos: {
@@ -264,3 +264,53 @@ describe('selectTodosFromMessages', () => {
expect(result?.items[1].status).toBe('completed');
});
});
+
+describe('selectCurrentTurnTodosFromMessages', () => {
+ const gtdMessage = (text: string, status: 'todo' | 'processing' | 'completed'): UIChatMessage =>
+ ({
+ id: `tool-${text}`,
+ role: 'tool',
+ content: 'Todos updated',
+ plugin: { identifier: 'lobe-gtd', apiName: 'createTodos', arguments: '{}' },
+ pluginState: {
+ todos: { items: [{ text, status }], updatedAt: '2026-04-20T00:00:00.000Z' },
+ },
+ }) as unknown as UIChatMessage;
+
+ const userMessage = (id: string, content = 'hi'): UIChatMessage =>
+ ({ id, role: 'user', content }) as UIChatMessage;
+
+ it('returns todos from the current turn only', () => {
+ const messages: UIChatMessage[] = [
+ userMessage('u1'),
+ gtdMessage('turn 1 task', 'completed'),
+ userMessage('u2'),
+ gtdMessage('turn 2 task', 'processing'),
+ ];
+
+ const result = selectCurrentTurnTodosFromMessages(messages);
+
+ expect(result?.items).toHaveLength(1);
+ expect(result?.items[0].text).toBe('turn 2 task');
+ });
+
+ it('returns undefined once a new user turn starts without its own todos', () => {
+ const messages: UIChatMessage[] = [
+ userMessage('u1'),
+ gtdMessage('previous turn task', 'completed'),
+ userMessage('u2'),
+ ];
+
+ const result = selectCurrentTurnTodosFromMessages(messages);
+
+ expect(result).toBeUndefined();
+ });
+
+ it('falls back to full history when no user message exists', () => {
+ const messages: UIChatMessage[] = [gtdMessage('greeting task', 'todo')];
+
+ const result = selectCurrentTurnTodosFromMessages(messages);
+
+ expect(result?.items[0].text).toBe('greeting task');
+ });
+});
diff --git a/src/store/chat/slices/message/selectors/dbMessage.ts b/src/store/chat/slices/message/selectors/dbMessage.ts
index 6b90baa5080..af573905b6d 100644
--- a/src/store/chat/slices/message/selectors/dbMessage.ts
+++ b/src/store/chat/slices/message/selectors/dbMessage.ts
@@ -279,6 +279,29 @@ export const selectTodosFromMessages = (
return undefined;
};
+/**
+ * Select todos from the current agent turn only — messages after the last
+ * user message. Intended for UI surfaces that should drop a stale/completed
+ * todos snapshot the moment a new user turn begins. If no user message exists
+ * yet (e.g. initial agent greeting), falls back to the full history.
+ *
+ * Do NOT use this for agent runtime step context — the runtime must see todos
+ * across turns so the agent remembers its plan between user messages.
+ */
+export const selectCurrentTurnTodosFromMessages = (
+ messages: UIChatMessage[],
+): StepContextTodos | undefined => {
+ let lastUserIndex = -1;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i].role === 'user') {
+ lastUserIndex = i;
+ break;
+ }
+ }
+ const scope = lastUserIndex >= 0 ? messages.slice(lastUserIndex + 1) : messages;
+ return selectTodosFromMessages(scope);
+};
+
/**
* Get current active chat's todos state from db messages
*/
@@ -305,5 +328,6 @@ export const dbMessageSelectors = {
latestUserMessage,
selectActivatedSkillsFromMessages,
selectActivatedToolIdsFromMessages,
+ selectCurrentTurnTodosFromMessages,
selectTodosFromMessages,
};