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.

πŸ› fix(chat-input): show the git branch of a staged project directory (#22159)

Arvin Xu981fcd6fc58b
diff --git a/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx
new file mode 100644
index 00000000000..b72c67f6d46
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx
@@ -0,0 +1,110 @@
+'use client';
+
+import type { DeviceGitWorktreeListItem } from '@lobechat/types';
+import { Icon, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { GitBranchIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useFetchGitBranch } from '@/store/device';
+
+import BranchSwitcher from './BranchSwitcher';
+import { gitChipStyles } from './gitChipStyles';
+import { getStagedBranchState } from './stagedBranchState';
+import { useStagedProjectGitTarget } from './useStagedProjectGitTarget';
+
+const styles = stylex.create({
+ branchGroup: { display: 'flex', flex: 'none', gap: '2px', alignItems: 'center' },
+ // Same footprint as the worktree trigger it stands in for, without the menu.
+ branchIcon: {
+ display: 'inline-flex',
+ flex: 'none',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '20px',
+ height: '22px',
+ color: cssVar.colorTextSecondary,
+ },
+ branchLabel: {
+ overflow: 'hidden',
+ maxWidth: '160px',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
+
+/** No worktree routing before the first send: nothing could record the pick. */
+const NO_WORKTREES: DeviceGitWorktreeListItem[] = [];
+
+interface StagedBranchStatusProps {
+ agentId: string;
+}
+
+/**
+ * The branch of the project directory a blank conversation is staged in, with
+ * an in-place checkout. Only the branch: the review, worktree and PR surfaces
+ * of `GitStatus` act on the conversation's recorded directory, which does not
+ * exist until the first send creates the topic.
+ */
+const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {
+ const { t } = useTranslation('device');
+ const target = useStagedProjectGitTarget(agentId);
+ const { data, isConfirmed, mutate } = useFetchGitBranch(target?.deviceId, target?.path);
+ const [open, setOpen] = useState(false);
+
+ const handleOptimisticCheckout = useCallback(
+ (branch: string) => {
+ void mutate({ branch, detached: false }, { revalidate: false });
+ },
+ [mutate],
+ );
+
+ const state = getStagedBranchState(data, isConfirmed);
+ if (!target || state === 'hidden') return null;
+ const branch = data!.branch!;
+
+ const trigger = (
+ <div {...stylex.props(gitChipStyles.trigger)}>
+ <span {...stylex.props(styles.branchLabel)}>{branch}</span>
+ </div>
+ );
+
+ return (
+ <>
+ <div {...stylex.props(gitChipStyles.separator)} />
+ <div {...stylex.props(styles.branchGroup)}>
+ <span {...stylex.props(styles.branchIcon)}>
+ <Icon icon={GitBranchIcon} size={13} />
+ </span>
+ {state === 'detached' ? (
+ <Tooltip title={t('workingDirectory.detachedHead', { sha: branch })}>{trigger}</Tooltip>
+ ) : state === 'confirming' ? (
+ <Tooltip title={t('workingDirectory.branchConfirming')}>{trigger}</Tooltip>
+ ) : (
+ <BranchSwitcher
+ agentId={agentId}
+ currentBranch={branch}
+ deviceId={target.deviceId}
+ isGithub={target.isGithub}
+ open={open}
+ path={target.path}
+ sourcePath={target.path}
+ topicId={null}
+ worktrees={NO_WORKTREES}
+ onAfterCheckout={() => void mutate()}
+ onOpenChange={setOpen}
+ onOptimisticCheckout={handleOptimisticCheckout}
+ >
+ <Tooltip title={branch}>{trigger}</Tooltip>
+ </BranchSwitcher>
+ )}
+ </div>
+ </>
+ );
+});
+
+StagedBranchStatus.displayName = 'StagedBranchStatus';
+
+export default StagedBranchStatus;
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index d76bfd5b99f..b7c38db5da0 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -17,6 +17,7 @@ import { useElectronStore } from '@/store/electron';
import { useTopicId } from '../hooks/useTopicId';
import GitStatus from './GitStatus';
+import StagedBranchStatus from './StagedBranchStatus';
import {
useActiveProjectDirectoryTopicId,
useStagedProjectDirectoryId,
@@ -123,13 +124,17 @@ WorkingDirectorySectionInner.displayName = 'WorkingDirectorySectionInner';
const WorkingDirectorySection = memo<WorkingDirectorySectionProps>(({ agentId }) => {
// A blank conversation staged in a project directory runs there, not in the
- // agent default this section resolves; the device switcher names it.
+ // agent default this section resolves; the device switcher names it, so only
+ // its branch shows here.
const stagedDirectoryId = useStagedProjectDirectoryId(agentId);
- if (stagedDirectoryId) return null;
return (
- <SafeBoundary minHeight={22} resetKeys={[agentId]}>
- <WorkingDirectorySectionInner agentId={agentId} />
+ <SafeBoundary minHeight={22} resetKeys={[agentId, stagedDirectoryId]}>
+ {stagedDirectoryId ? (
+ <StagedBranchStatus agentId={agentId} />
+ ) : (
+ <WorkingDirectorySectionInner agentId={agentId} />
+ )}
</SafeBoundary>
);
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/stagedBranchState.test.ts b/src/features/ChatInput/ControlBar/__tests__/stagedBranchState.test.ts
new file mode 100644
index 00000000000..869ce699a3d
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/stagedBranchState.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { getStagedBranchState } from '../stagedBranchState';
+
+describe('getStagedBranchState', () => {
+ it('holds a hydrated branch read-only until this session confirms it', () => {
+ expect(getStagedBranchState({ branch: 'main', detached: false }, false)).toBe('confirming');
+ });
+
+ it('lets a confirmed branch switch', () => {
+ expect(getStagedBranchState({ branch: 'main', detached: false }, true)).toBe('switchable');
+ });
+
+ it('shows a detached head without a switcher', () => {
+ expect(getStagedBranchState({ branch: 'abc1234', detached: true }, true)).toBe('detached');
+ });
+
+ it('hides when the directory is not a repo or not read yet', () => {
+ expect(getStagedBranchState({}, true)).toBe('hidden');
+ expect(getStagedBranchState(undefined, false)).toBe('hidden');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
index 48e6d808d86..a0b8c3044cd 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -14,6 +14,8 @@ const testState = vi.hoisted(() => ({
},
chat: {
activeTopicId: undefined as string | undefined,
+ pendingNewTopicDirectory: undefined as
+ { agentId: string; projectWorkingDirectoryId: string } | undefined,
topic: undefined as ChatTopic | undefined,
updateTopicMetadata: vi.fn(),
},
@@ -72,6 +74,7 @@ describe('useCommitWorkingDirectory β€” localTarget', () => {
testState.agent.updateAgentConfigById = vi.fn();
testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();
testState.chat.activeTopicId = undefined;
+ testState.chat.pendingNewTopicDirectory = undefined;
testState.chat.topic = undefined;
testState.chat.updateTopicMetadata = vi.fn();
testState.currentDeviceId = 'this-machine';
@@ -82,6 +85,25 @@ describe('useCommitWorkingDirectory β€” localTarget', () => {
};
});
+ it('refuses a worktree pick while a blank conversation is staged in a project directory', async () => {
+ // No topic yet, so the write would otherwise land on the agent default β€”
+ // a directory this conversation will not run in.
+ testState.agent.agencyConfig = { boundDeviceId: 'this-machine', executionTarget: 'device' };
+ testState.effective.agencyConfig = testState.agent.agencyConfig;
+ testState.chat.pendingNewTopicDirectory = {
+ agentId: 'agent-id',
+ projectWorkingDirectoryId: 'directory',
+ };
+
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await expect(
+ result.current.commit({ path: '/repo', git: { activeWorktree: '/repo-worktree' } }),
+ ).rejects.toThrow();
+
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ expect(testState.agent.updateAgentRuntimeEnvConfigById).not.toHaveBeenCalled();
+ });
+
it('keeps a project-bound source directory while allowing worktree selection', async () => {
testState.chat.activeTopicId = 'topic';
testState.chat.topic = {
diff --git a/src/features/ChatInput/ControlBar/__tests__/useStagedProjectGitTarget.test.ts b/src/features/ChatInput/ControlBar/__tests__/useStagedProjectGitTarget.test.ts
new file mode 100644
index 00000000000..21182adbd41
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/useStagedProjectGitTarget.test.ts
@@ -0,0 +1,79 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useStagedProjectGitTarget } from '../useStagedProjectGitTarget';
+
+const testState = vi.hoisted(() => ({
+ currentDeviceId: undefined as string | undefined,
+ directories: [] as { deviceId: string | null; id: string; path: string }[],
+ directoryId: undefined as string | undefined,
+ isDesktop: false,
+ repoType: 'git' as 'git' | 'github' | undefined,
+}));
+
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return testState.isDesktop;
+ },
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (s: { gatewayDeviceInfo?: { deviceId?: string } }) => unknown) =>
+ selector({ gatewayDeviceInfo: { deviceId: testState.currentDeviceId } }),
+}));
+
+vi.mock('../useProjectTopicDirectory', () => ({
+ useStagedProjectDirectory: () => ({
+ directories: testState.directories,
+ directoryId: testState.directoryId,
+ }),
+}));
+
+vi.mock('../useRepoType', () => ({ useRepoType: () => testState.repoType }));
+
+describe('useStagedProjectGitTarget', () => {
+ beforeEach(() => {
+ testState.currentDeviceId = undefined;
+ testState.directories = [
+ { deviceId: 'other', id: 'dir-0', path: '/Users/me/other' },
+ { deviceId: 'm4-pro', id: 'dir-1', path: '/Users/me/repo' },
+ ];
+ testState.directoryId = 'dir-1';
+ testState.isDesktop = false;
+ testState.repoType = 'git';
+ });
+
+ it('reads the staged directory on its own device', () => {
+ const { result } = renderHook(() => useStagedProjectGitTarget('agent-1'));
+
+ expect(result.current).toEqual({ deviceId: 'm4-pro', isGithub: false, path: '/Users/me/repo' });
+ });
+
+ it('probes this desktop locally when the directory lives here', () => {
+ testState.isDesktop = true;
+ testState.currentDeviceId = 'm4-pro';
+ testState.repoType = 'github';
+
+ const { result } = renderHook(() => useStagedProjectGitTarget('agent-1'));
+
+ expect(result.current).toEqual({ deviceId: undefined, isGithub: true, path: '/Users/me/repo' });
+ });
+
+ it('still targets a directory whose repo type no picker cache recorded', () => {
+ // A directory bound in Project Settings on a remote device never enters that
+ // device's picker cache; the branch probe decides whether it is a repo.
+ testState.repoType = undefined;
+
+ const { result } = renderHook(() => useStagedProjectGitTarget('agent-1'));
+
+ expect(result.current).toEqual({ deviceId: 'm4-pro', isGithub: false, path: '/Users/me/repo' });
+ });
+
+ it('has no target when nothing is staged', () => {
+ testState.directoryId = undefined;
+
+ const { result } = renderHook(() => useStagedProjectGitTarget('agent-1'));
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/stagedBranchState.ts b/src/features/ChatInput/ControlBar/stagedBranchState.ts
new file mode 100644
index 00000000000..7558306bcaf
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/stagedBranchState.ts
@@ -0,0 +1,15 @@
+import type { GitBranchSummary } from '@/services/git';
+
+/**
+ * What the staged bar may do with a branch read. A hydrated row from the last
+ * session is only a label: the switcher would treat it as current and skip a
+ * checkout to that branch, so switching waits for this session's probe.
+ */
+export const getStagedBranchState = (
+ data: GitBranchSummary | undefined,
+ isConfirmed: boolean,
+): 'hidden' | 'detached' | 'confirming' | 'switchable' => {
+ if (!data?.branch) return 'hidden';
+ if (data.detached) return 'detached';
+ return isConfirmed ? 'switchable' : 'confirming';
+};
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 3ece5ad1e80..3b2d456ff6a 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -14,6 +14,8 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useDeviceStore } from '@/store/device';
import { getElectronStoreState, useElectronStore } from '@/store/electron';
+import { stagedProjectDirectoryIdSelector } from './useProjectTopicDirectory';
+
export interface CommitWorkingDirectoryOptions extends CommitAgentDefaultOptions {
/**
* Persist against the `local` execution target on this machine, regardless of
@@ -119,6 +121,9 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
const activeTopic = useChatStore((s) =>
activeTopicId ? topicSelectors.getTopicById(activeTopicId)(s) : undefined,
);
+ // A blank conversation staged in a project directory has no topic to record
+ // a pick on, and the agent default is not where it will run.
+ const stagedDirectoryId = useChatStore(stagedProjectDirectoryIdSelector(agentId, activeTopicId));
const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);
@@ -312,6 +317,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
const effectivePath = getWorkingDirEffectivePath(normalizedEntry);
if (!normalizedEntry || !effectivePath) return;
+ if (stagedDirectoryId) throw new Error(t('directories.boundRoot', { ns: 'project' }));
if (activeTopic?.projectWorkingDirectoryId) {
const source = getWorkingDirSourcePath(
activeTopic.metadata?.workingDirectoryConfig ?? activeTopic.metadata?.workingDirectory,
@@ -342,7 +348,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
}
await run();
},
- [activeTopic, isHetero, t, writeCwd],
+ [activeTopic, isHetero, stagedDirectoryId, t, writeCwd],
);
/**
diff --git a/src/features/ChatInput/ControlBar/useStagedProjectGitTarget.ts b/src/features/ChatInput/ControlBar/useStagedProjectGitTarget.ts
new file mode 100644
index 00000000000..7e754d505a9
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useStagedProjectGitTarget.ts
@@ -0,0 +1,39 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useElectronStore } from '@/store/electron';
+
+import { useStagedProjectDirectory } from './useProjectTopicDirectory';
+import { useRepoType } from './useRepoType';
+
+export interface StagedProjectGitTarget {
+ /** Undefined for this desktop, which probes its own filesystem over IPC. */
+ deviceId?: string;
+ isGithub: boolean;
+ path: string;
+}
+
+/**
+ * Where a blank conversation staged in a project directory reads its git
+ * status: that directory, on its own device. The conversation will run there,
+ * not in the agent default the control bar otherwise resolves. The repo type is
+ * not a gate: a directory bound in Project Settings on a remote device never
+ * enters that device's picker cache, so it would stay unknown. The branch probe
+ * itself answers empty for a directory that is not a repo.
+ */
+export const useStagedProjectGitTarget = (agentId: string): StagedProjectGitTarget | undefined => {
+ const { directories, directoryId } = useStagedProjectDirectory(agentId);
+ const directory = directories.find((d) => d.id === directoryId);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
+ const deviceId = directory?.deviceId ?? undefined;
+ const repoType = useRepoType(directory?.path, deviceId);
+
+ if (!directory?.path) return;
+
+ const isLocalDevice = isDesktop && !!deviceId && deviceId === currentDeviceId;
+
+ return {
+ deviceId: isLocalDevice ? undefined : deviceId,
+ isGithub: repoType === 'github',
+ path: directory.path,
+ };
+};