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): snapshot topic branch/PR at send time, not on open (#16785)

Arvin Xu887a4a75cf9c
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index e804d074abc..3eedffe468d 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -1,18 +1,13 @@
-import type { WorkingDirConfig, WorkingDirGithubState } from '@lobechat/types';
-import { getWorkingDirEffectivePath } from '@lobechat/types';
import { Icon, Tooltip } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import isEqual from 'fast-deep-equal';
import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RingLoadingIcon from '@/components/RingLoading';
import { electronSystemService } from '@/services/electron/system';
-import { type GitLinkedPRSummary, gitService } from '@/services/git';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
+import { gitService } from '@/services/git';
import {
useFetchGitAheadBehind,
useFetchGitBranch,
@@ -151,16 +146,6 @@ const styles = createStaticStyles(({ css }) => {
};
});
-const toGithubMetadata = (prData?: GitLinkedPRSummary): WorkingDirGithubState | undefined => {
- if (!prData) return undefined;
-
- return {
- ...(prData.extraCount === undefined ? {} : { extraPullRequestCount: prData.extraCount }),
- pullRequest: prData.pullRequest ?? null,
- pullRequestStatus: prData.pullRequestStatus ?? (prData.ghMissing ? 'gh-missing' : 'ok'),
- };
-};
-
interface GitStatusProps {
/** When set, git status / branch switch / pull / push all run against this
* remote device via RPC. Omit for the local machine (talks over IPC). */
@@ -192,11 +177,6 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d
const [switcherOpen, setSwitcherOpen] = useState(false);
const [pulling, setPulling] = useState(false);
const [pushing, setPushing] = useState(false);
- const activeTopicId = useChatStore((s) => s.activeTopicId);
- const activeTopicMetadata = useChatStore((s) =>
- s.activeTopicId ? topicSelectors.getTopicById(s.activeTopicId)(s)?.metadata : undefined,
- );
- const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);
@@ -238,53 +218,6 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d
[mutateBranch],
);
- useEffect(() => {
- if (!activeTopicId || !activeTopicMetadata || !isGithub || !branch || detached || !prData) {
- return;
- }
-
- const currentConfig = activeTopicMetadata.workingDirectoryConfig;
- const currentWorkingDirectory =
- getWorkingDirEffectivePath(currentConfig) ?? activeTopicMetadata.workingDirectory;
- if (currentWorkingDirectory !== path) return;
-
- const github = toGithubMetadata(prData);
- if (!github) return;
-
- const source = currentConfig?.path ?? sourcePath ?? path;
- const isWorktree = source !== path;
- const git: NonNullable<WorkingDirConfig['git']> = {
- ...currentConfig?.git,
- branch,
- github,
- isWorktree,
- };
- if (detached === undefined) delete git.detached;
- else git.detached = detached;
- if (isWorktree) git.activeWorktree = path;
- else delete git.activeWorktree;
-
- const nextConfig: WorkingDirConfig = {
- ...currentConfig,
- git,
- path: source,
- repoType: 'github',
- };
-
- if (isEqual(currentConfig, nextConfig)) return;
- void updateTopicMetadata(activeTopicId, { workingDirectoryConfig: nextConfig });
- }, [
- activeTopicId,
- activeTopicMetadata,
- branch,
- detached,
- isGithub,
- path,
- prData,
- sourcePath,
- updateTopicMetadata,
- ]);
-
const syncBusy = pulling || pushing;
const handlePull = useCallback(async () => {
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 9a21cde02e7..1cd2e51b748 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -26,12 +26,6 @@ const gitHookMocks = vi.hoisted(() => ({
useFetchGitWorktrees: vi.fn(),
}));
-const chatStoreMock = vi.hoisted(() => ({
- activeTopicId: undefined as string | undefined,
- topics: {} as Record<string, { metadata?: Record<string, unknown> }>,
- updateTopicMetadata: vi.fn(),
-}));
-
vi.mock('../BranchSwitcher', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
@@ -48,16 +42,6 @@ vi.mock('@/store/device', () => ({
useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,
}));
-vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: typeof chatStoreMock) => unknown) => selector(chatStoreMock),
-}));
-
-vi.mock('@/store/chat/selectors', () => ({
- topicSelectors: {
- getTopicById: (id: string) => (state: typeof chatStoreMock) => state.topics[id],
- },
-}));
-
vi.mock('@/store/global', () => ({
useGlobalStore: (selector: (state: typeof globalStoreMock) => unknown) =>
selector(globalStoreMock),
@@ -113,8 +97,6 @@ vi.mock('react-i18next', () => ({
beforeEach(() => {
vi.clearAllMocks();
- chatStoreMock.activeTopicId = undefined;
- chatStoreMock.topics = {};
globalStoreMock.status.showRightPanel = false;
globalStoreMock.status.workingSidebarTab = 'resources';
@@ -172,20 +154,7 @@ describe('GitStatus', () => {
expect(globalStoreMock.toggleRightPanel).toHaveBeenCalledWith(true);
});
- it('persists linked GitHub PR metadata into the active topic working directory config', async () => {
- chatStoreMock.activeTopicId = 'topic-1';
- chatStoreMock.topics = {
- 'topic-1': {
- metadata: {
- workingDirectory: '/repo',
- workingDirectoryConfig: {
- git: { branch: 'old-branch' },
- path: '/repo',
- repoType: 'github',
- },
- },
- },
- };
+ it('renders the linked GitHub PR number as a live display (no topic write)', async () => {
gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
data: {
pullRequest: {
@@ -203,29 +172,11 @@ describe('GitStatus', () => {
render(<GitStatus isGithub agentId="agent-1" path="/repo" />);
+ // Pure display: the chip shows the current branch's PR number. Persisting it
+ // onto the topic now happens at send time (see snapshotWorkingDirGit), so
+ // opening a topic must never mutate its stored branch/PR here.
await waitFor(() => {
- expect(chatStoreMock.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
- workingDirectoryConfig: {
- git: {
- branch: 'fix/remote-review',
- detached: false,
- github: {
- pullRequest: {
- ciStatus: 'pending',
- mergeStateStatus: 'CLEAN',
- number: 123,
- state: 'OPEN',
- title: 'Improve worktree handling',
- url: 'https://github.com/lobehub/lobehub/pull/123',
- },
- pullRequestStatus: 'ok',
- },
- isWorktree: false,
- },
- path: '/repo',
- repoType: 'github',
- },
- });
+ expect(screen.getByText('#123')).toBeInTheDocument();
});
});
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index bdfdaceeb31..6b5c81e53b5 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -8,6 +8,7 @@ import {
import { Flexbox, Icon, Popover, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, keyframes, useTheme } from 'antd-style';
import { CheckCircle2, Hand, HashIcon, MessageSquareDashed, TriangleAlert } from 'lucide-react';
+import type { CSSProperties } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -46,6 +47,19 @@ const rippleAnim = keyframes`
}
`;
+// Base UI Popover plays an opacity/scale enter+exit transition driven by these
+// CSS vars on the positioner. Zero them so the meta hover card appears instantly
+// instead of easing in β€” the hover-intent delay (`mouseEnterDelay`) still gates
+// when it shows. `styles.root` maps to the positioner (inline style β†’ wins over
+// the library's default without a specificity fight).
+const META_HOVER_CARD_STYLES = {
+ content: { padding: 12 },
+ root: {
+ '--lobe-popover-animation-duration': '0ms',
+ '--lobe-popover-animation-duration-exit': '0ms',
+ } as CSSProperties,
+};
+
const styles = createStaticStyles(({ css }) => ({
unreadWrapper: css`
position: relative;
@@ -450,9 +464,9 @@ const TopicItem = memo<TopicItemProps>(
<Popover
arrow={false}
content={<MetaHoverCard metadata={metadata} title={title} />}
- mouseEnterDelay={0.4}
+ mouseEnterDelay={0.8}
placement={'right'}
- styles={{ content: { padding: 12 } }}
+ styles={META_HOVER_CARD_STYLES}
trigger={'hover'}
>
<div>{navItem}</div>
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts
new file mode 100644
index 00000000000..041c4b08090
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts
@@ -0,0 +1,242 @@
+import type * as LobechatConstModule from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { snapshotTopicWorkingDirGit } from '../snapshotWorkingDirGit';
+
+const mockConstEnv = vi.hoisted(() => ({ isDesktop: true }));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<typeof LobechatConstModule>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockConstEnv.isDesktop;
+ },
+ };
+});
+
+const gitMocks = vi.hoisted(() => ({
+ getGitBranch: vi.fn(),
+ getLinkedPullRequest: vi.fn(),
+}));
+
+vi.mock('@/services/git', () => ({
+ gitService: {
+ getGitBranch: gitMocks.getGitBranch,
+ getLinkedPullRequest: gitMocks.getLinkedPullRequest,
+ },
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({}),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => undefined,
+ },
+}));
+
+const env = vi.hoisted(() => ({
+ currentDeviceId: undefined as string | undefined,
+ targetDeviceId: undefined as string | undefined,
+}));
+
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({
+ gatewayDeviceInfo: env.currentDeviceId ? { deviceId: env.currentDeviceId } : undefined,
+ }),
+}));
+
+vi.mock('@/helpers/agentWorkingDirectory', () => ({
+ resolveTargetDeviceId: () => env.targetDeviceId,
+}));
+
+const deviceMocks = vi.hoisted(() => ({
+ workingDirs: [] as { path: string; repoType?: string }[],
+}));
+
+vi.mock('@/store/device', () => ({
+ deviceSelectors: {
+ getDeviceWorkingDirs: () => () => deviceMocks.workingDirs,
+ },
+ getDeviceStoreState: () => ({}),
+}));
+
+const electronGitMocks = vi.hoisted(() => ({ detectRepoType: vi.fn() }));
+
+vi.mock('@/services/electron/git', () => ({
+ electronGitService: { detectRepoType: electronGitMocks.detectRepoType },
+}));
+
+const topicMocks = vi.hoisted(() => ({ getTopicById: vi.fn() }));
+
+vi.mock('../../../../topic/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (state: unknown) => topicMocks.getTopicById(id, state),
+ },
+}));
+
+const PR = {
+ ciStatus: 'pending' as const,
+ number: 123,
+ state: 'OPEN',
+ title: 'Improve worktree handling',
+ url: 'https://github.com/lobehub/lobehub/pull/123',
+};
+
+const githubTopic = {
+ metadata: {
+ workingDirectory: '/repo',
+ workingDirectoryConfig: {
+ git: { branch: 'old-branch' },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+};
+
+const makeGet = () => {
+ const updateTopicMetadata = vi.fn().mockResolvedValue(undefined);
+ const get = () => ({ updateTopicMetadata }) as any;
+ return { get, updateTopicMetadata };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockConstEnv.isDesktop = true;
+ env.currentDeviceId = undefined;
+ env.targetDeviceId = undefined;
+ deviceMocks.workingDirs = [];
+ electronGitMocks.detectRepoType.mockResolvedValue(undefined);
+ gitMocks.getGitBranch.mockResolvedValue({ branch: 'fix/remote-review', detached: false });
+ gitMocks.getLinkedPullRequest.mockResolvedValue({ pullRequest: PR, pullRequestStatus: 'ok' });
+});
+
+describe('snapshotTopicWorkingDirGit', () => {
+ it('snapshots the live branch + linked PR onto the topic config', async () => {
+ topicMocks.getTopicById.mockReturnValue(githubTopic);
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'fix/remote-review',
+ github: { pullRequest: PR, pullRequestStatus: 'ok' },
+ isWorktree: false,
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('snapshots a legacy workingDirectory-only topic (repoType from device workingDirs)', async () => {
+ // Older topics persist only `workingDirectory` with no `workingDirectoryConfig`;
+ // the repo type must come from the device, not the (absent) stored config.
+ topicMocks.getTopicById.mockReturnValue({ metadata: { workingDirectory: '/repo' } });
+ deviceMocks.workingDirs = [{ path: '/repo', repoType: 'github' }];
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'fix/remote-review',
+ github: { pullRequest: PR, pullRequestStatus: 'ok' },
+ isWorktree: false,
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('resolves repoType via a local filesystem probe when the device cache misses', async () => {
+ env.currentDeviceId = 'dev-1';
+ env.targetDeviceId = 'dev-1';
+ deviceMocks.workingDirs = [];
+ electronGitMocks.detectRepoType.mockResolvedValue('github');
+ topicMocks.getTopicById.mockReturnValue({ metadata: { workingDirectory: '/repo' } });
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(electronGitMocks.detectRepoType).toHaveBeenCalledWith('/repo');
+ expect(updateTopicMetadata).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({
+ workingDirectoryConfig: expect.objectContaining({ repoType: 'github' }),
+ }),
+ );
+ });
+
+ it('does nothing for a legacy topic whose device repoType is non-github', async () => {
+ topicMocks.getTopicById.mockReturnValue({ metadata: { workingDirectory: '/repo' } });
+ deviceMocks.workingDirs = [{ path: '/repo', repoType: 'git' }];
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(gitMocks.getGitBranch).not.toHaveBeenCalled();
+ expect(updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for a non-github repo', async () => {
+ topicMocks.getTopicById.mockReturnValue({
+ metadata: { workingDirectoryConfig: { path: '/repo', repoType: 'git' } },
+ });
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(gitMocks.getGitBranch).not.toHaveBeenCalled();
+ expect(updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('leaves the prior snapshot on a detached HEAD (no branch to query)', async () => {
+ topicMocks.getTopicById.mockReturnValue(githubTopic);
+ gitMocks.getGitBranch.mockResolvedValue({ branch: 'abc1234', detached: true });
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(gitMocks.getLinkedPullRequest).not.toHaveBeenCalled();
+ expect(updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('skips the write when the resolved config is unchanged (idempotent)', async () => {
+ topicMocks.getTopicById.mockReturnValue({
+ metadata: {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'fix/remote-review',
+ github: { pullRequest: PR, pullRequestStatus: 'ok' },
+ isWorktree: false,
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ });
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('bails on web (no deviceId, not desktop) without probing git', async () => {
+ mockConstEnv.isDesktop = false;
+ topicMocks.getTopicById.mockReturnValue(githubTopic);
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(gitMocks.getGitBranch).not.toHaveBeenCalled();
+ expect(updateTopicMetadata).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index 60e56d8e3d9..ede27bb87e7 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -5,6 +5,7 @@ import debug from 'debug';
import type { AgentRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
+import { snapshotTopicWorkingDirGit } from '@/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopAgentCompleted } from '@/store/chat/utils/desktopNotification';
import { markdownToTxt } from '@/utils/markdownToTxt';
@@ -183,6 +184,12 @@ export const buildRunLifecycle = (
const { isCreateNewTopic, topicId, assistantMessageId } = event;
if (!topicId) return;
+ // Snapshot the working directory's live branch + linked PR onto the topic.
+ // Anchored HERE (send) rather than in the ControlBar's mount effect so that
+ // merely opening a topic never re-stamps its historical branch/PR. Slow gh
+ // leg β†’ fire-and-forget; it only patches topic metadata, idempotently.
+ void snapshotTopicWorkingDirGit(get, { agentId, topicId }).catch(() => {});
+
// Dev-only fast path: slice the first user message instead of calling the
// LLM. Only honored in non-production builds. Relocated verbatim.
const shouldSliceTopicTitle =
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
new file mode 100644
index 00000000000..3dc49b46968
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
@@ -0,0 +1,126 @@
+import { isDesktop } from '@lobechat/const';
+import type { WorkingDirConfig, WorkingDirGithubState } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
+import { electronGitService } from '@/services/electron/git';
+import { type GitLinkedPRSummary, gitService } from '@/services/git';
+import { getAgentStoreState } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import type { ChatStore } from '@/store/chat/store';
+import { deviceSelectors, getDeviceStoreState } from '@/store/device';
+import { getElectronStoreState } from '@/store/electron';
+
+import { topicSelectors } from '../../../topic/selectors';
+
+/**
+ * Resolve the working directory's repo type the SAME way the ControlBar's
+ * `useRepoType` does β€” from the device's persisted `workingDirs[].repoType`, then
+ * (local machine only) a filesystem probe. Deliberately NOT read off the topic's
+ * stored `workingDirectoryConfig.repoType`: legacy topics persist only
+ * `workingDirectory` with no config, so a config-based gate would skip them and
+ * never refresh their branch/PR snapshot.
+ */
+const resolveRepoType = async (params: {
+ isLocalDevice: boolean;
+ path: string;
+ targetDeviceId?: string;
+}): Promise<'git' | 'github' | undefined> => {
+ const { isLocalDevice, path, targetDeviceId } = params;
+ const fromDevice = deviceSelectors
+ .getDeviceWorkingDirs(targetDeviceId)(getDeviceStoreState())
+ .find((d) => d.path === path || getWorkingDirEffectivePath(d) === path)?.repoType;
+ if (fromDevice) return fromDevice;
+ // A remote device's filesystem isn't reachable here β€” only probe the local one.
+ if (isLocalDevice) return electronGitService.detectRepoType(path);
+ return undefined;
+};
+
+const toGithubMetadata = (prData?: GitLinkedPRSummary): WorkingDirGithubState | undefined => {
+ if (!prData) return undefined;
+
+ return {
+ ...(prData.extraCount === undefined ? {} : { extraPullRequestCount: prData.extraCount }),
+ pullRequest: prData.pullRequest ?? null,
+ pullRequestStatus: prData.pullRequestStatus ?? (prData.ghMissing ? 'gh-missing' : 'ok'),
+ };
+};
+
+/**
+ * Capture the working directory's live branch + linked PR onto the topic's
+ * `workingDirectoryConfig` at SEND time.
+ *
+ * This is the sole writer of the branch/PR snapshot into topic metadata. It used
+ * to live as a reactive effect in the ControlBar's `GitStatus`, but that fired on
+ * every mount β€” so merely OPENING a topic re-stamped it with whatever branch the
+ * shared working directory happened to be on, clobbering the historical snapshot.
+ * Anchoring it to `afterUserMessagePersisted` matches the product contract ("the
+ * chat branch reflects the last-used active branch; sending a message updates
+ * it") and leaves `GitStatus` a pure live display of the current directory.
+ *
+ * Fire-and-forget: the `gh pr list` leg is slow (8s timeout), so callers must not
+ * await it on the send path. It only ever patches topic metadata, idempotently.
+ */
+export const snapshotTopicWorkingDirGit = async (
+ get: () => ChatStore,
+ { agentId, topicId }: { agentId: string; topicId: string },
+): Promise<void> => {
+ const topic = topicSelectors.getTopicById(topicId)(get());
+ if (!topic) return;
+
+ const currentConfig = topic.metadata?.workingDirectoryConfig;
+ const path = getWorkingDirEffectivePath(currentConfig) ?? topic.metadata?.workingDirectory;
+ if (!path) return;
+
+ const agentState = getAgentStoreState();
+ const agencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(agentState);
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
+ const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;
+ const deviceId = isLocalDevice ? undefined : targetDeviceId;
+
+ // Same transport gate as `gitHooks.isEnabled`: a local read needs `isDesktop`,
+ // a remote read needs a `deviceId`. Neither β†’ nothing to probe.
+ if (!deviceId && !isDesktop) return;
+
+ // Branch/PR snapshot is only meaningful for a GitHub repo β€” mirror GitStatus's
+ // `isGithub` gate (non-github repos never show a PR chip). Resolve it live (the
+ // config's own `repoType` may be absent on legacy topics); the stored value is
+ // still a valid fast path when present.
+ const repoType =
+ currentConfig?.repoType ?? (await resolveRepoType({ isLocalDevice, path, targetDeviceId }));
+ if (repoType !== 'github') return;
+
+ const branchInfo = await gitService.getGitBranch({ deviceId, path });
+ const branch = branchInfo?.branch;
+ const detached = branchInfo?.detached;
+ // No branch ref to query (unprobed / detached HEAD) β†’ leave the prior snapshot.
+ if (!branch || detached) return;
+
+ const prData = await gitService.getLinkedPullRequest({ branch, deviceId, path });
+ const github = toGithubMetadata(prData);
+ if (!github) return;
+
+ const source = currentConfig?.path ?? path;
+ const isWorktree = source !== path;
+ const git: NonNullable<WorkingDirConfig['git']> = {
+ ...currentConfig?.git,
+ branch,
+ github,
+ isWorktree,
+ };
+ delete git.detached;
+ if (isWorktree) git.activeWorktree = path;
+ else delete git.activeWorktree;
+
+ const nextConfig: WorkingDirConfig = {
+ ...currentConfig,
+ git,
+ path: source,
+ repoType: 'github',
+ };
+
+ if (isEqual(currentConfig, nextConfig)) return;
+ await get().updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });
+};