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.

Refresh topic PR status on detail (#16827)

Arvin Xu0d03f9b20155
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 7727f4aca42..04f400d9160 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -75,6 +75,7 @@ export default class GitController extends ControllerModule {
async getLinkedPullRequest(payload: {
branch: string;
path: string;
+ pullRequestNumber?: number;
}): Promise<GitLinkedPullRequestResult> {
return computeLinkedPullRequest(payload);
}
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 81c93bf7348..9c0c8aedd89 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -148,12 +148,20 @@ export const deviceRouter = router({
}),
gitLinkedPullRequest: deviceProcedure
- .input(z.object({ branch: z.string(), deviceId: z.string(), path: z.string() }))
+ .input(
+ z.object({
+ branch: z.string(),
+ deviceId: z.string(),
+ path: z.string(),
+ pullRequestNumber: z.number().optional(),
+ }),
+ )
.query(async ({ ctx, input }) => {
const result = await deviceGateway.gitLinkedPullRequest({
branch: input.branch,
deviceId: input.deviceId,
path: input.path,
+ pullRequestNumber: input.pullRequestNumber,
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 75d72154820..d0af7300073 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -289,12 +289,14 @@ export class DeviceGateway {
branch: string;
deviceId: string;
path: string;
+ pullRequestNumber?: number;
userId: string;
workspaceId?: string;
}) {
return this.invokeGitRead<DeviceGitLinkedPullRequestResult>('getLinkedPullRequest', params, {
branch: params.branch,
path: params.path,
+ pullRequestNumber: params.pullRequestNumber,
});
}
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index e82e9306964..af5c571ae26 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -135,7 +135,9 @@ export const executeDeviceRpc = async (
}
case 'getLinkedPullRequest': {
- return getLinkedPullRequest(params as { branch: string; path: string });
+ return getLinkedPullRequest(
+ params as { branch: string; path: string; pullRequestNumber?: number },
+ );
}
case 'getGitWorkingTreeStatus': {
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index 7c8a93d1158..60d8892067c 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -23,9 +23,9 @@ export interface GitLinkedPullRequest {
export type GitLinkedPullRequestLookupStatus = 'ok' | 'gh-missing' | 'error';
export interface GitLinkedPullRequestResult {
- /** Additional open PRs targeting the same head branch, beyond the primary one */
+ /** Additional PRs targeting the same head branch, beyond the primary one */
extraCount?: number;
- /** Null when no open PR is linked to the branch */
+ /** Null when no PR is linked to the branch */
pullRequest: GitLinkedPullRequest | null;
/** 'ok' β€” lookup succeeded; 'gh-missing' β€” gh CLI unavailable / not authed; 'error' β€” other failure */
status: GitLinkedPullRequestLookupStatus;
diff --git a/packages/local-file-shell/src/git/__tests__/info.test.ts b/packages/local-file-shell/src/git/__tests__/info.test.ts
new file mode 100644
index 00000000000..81f716914db
--- /dev/null
+++ b/packages/local-file-shell/src/git/__tests__/info.test.ts
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getLinkedPullRequest } from '../info';
+
+const childProcessMocks = vi.hoisted(() => ({
+ execFileAsync: vi.fn(),
+}));
+
+vi.mock('node:child_process', () => {
+ const execFile = Object.assign(vi.fn(), {
+ [Symbol.for('nodejs.util.promisify.custom')]: childProcessMocks.execFileAsync,
+ });
+
+ return { execFile };
+});
+
+describe('getLinkedPullRequest', () => {
+ beforeEach(() => {
+ childProcessMocks.execFileAsync.mockReset();
+ });
+
+ it('queries the preserved PR number directly when provided', async () => {
+ childProcessMocks.execFileAsync.mockResolvedValue({
+ stderr: '',
+ stdout: JSON.stringify({
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ mergeable: 'MERGEABLE',
+ mergedAt: '2026-07-07T09:00:00Z',
+ number: 123,
+ reviewDecision: 'APPROVED',
+ state: 'MERGED',
+ statusCheckRollup: [{ conclusion: 'SUCCESS' }],
+ title: 'fix: stop stale running topics',
+ url: 'https://github.com/lobehub/lobehub/pull/123',
+ }),
+ });
+
+ const result = await getLinkedPullRequest({
+ branch: 'fix/topic-running',
+ path: '/repo',
+ pullRequestNumber: 123,
+ });
+
+ expect(childProcessMocks.execFileAsync).toHaveBeenCalledWith(
+ 'gh',
+ expect.arrayContaining(['pr', 'view', '123', '--json']),
+ { cwd: '/repo', timeout: 8000 },
+ );
+ expect(childProcessMocks.execFileAsync.mock.calls[0]![1]).not.toContain('--head');
+ expect(result.pullRequest).toMatchObject({ mergedAt: '2026-07-07T09:00:00Z', number: 123 });
+ });
+
+ it('queries all PR states so merged pull requests can refresh topic metadata', async () => {
+ childProcessMocks.execFileAsync.mockResolvedValue({
+ stderr: '',
+ stdout: JSON.stringify([
+ {
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ mergeable: 'MERGEABLE',
+ mergedAt: '2026-07-07T09:00:00Z',
+ number: 123,
+ reviewDecision: 'APPROVED',
+ state: 'MERGED',
+ statusCheckRollup: [{ conclusion: 'SUCCESS' }],
+ title: 'fix: stop stale running topics',
+ url: 'https://github.com/lobehub/lobehub/pull/123',
+ },
+ ]),
+ });
+
+ const result = await getLinkedPullRequest({ branch: 'fix/topic-running', path: '/repo' });
+
+ expect(childProcessMocks.execFileAsync).toHaveBeenCalledWith(
+ 'gh',
+ expect.arrayContaining(['--head', 'fix/topic-running', '--state', 'all']),
+ { cwd: '/repo', timeout: 8000 },
+ );
+ expect(result).toEqual({
+ extraCount: 0,
+ pullRequest: {
+ ciStatus: 'success',
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ mergeable: 'MERGEABLE',
+ mergedAt: '2026-07-07T09:00:00Z',
+ number: 123,
+ reviewDecision: 'APPROVED',
+ state: 'MERGED',
+ title: 'fix: stop stale running topics',
+ url: 'https://github.com/lobehub/lobehub/pull/123',
+ },
+ status: 'ok',
+ });
+ });
+});
diff --git a/packages/local-file-shell/src/git/info.ts b/packages/local-file-shell/src/git/info.ts
index 691acf75551..89687958c1a 100644
--- a/packages/local-file-shell/src/git/info.ts
+++ b/packages/local-file-shell/src/git/info.ts
@@ -36,6 +36,9 @@ type GithubPullRequestPayload = {
url: string;
};
+const GITHUB_PULL_REQUEST_FIELDS =
+ 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup';
+
const failureConclusions = new Set([
'action_required',
'cancelled',
@@ -132,17 +135,30 @@ export const getGitBranch = async (dirPath: string): Promise<GitBranchInfo> => {
};
/**
- * Query `gh` CLI for an open pull request whose head branch matches `branch`.
- * Returns `status: 'gh-missing'` when `gh` is unavailable / not authed.
+ * Query `gh` CLI for a saved PR number when present; otherwise fall back to the
+ * PR whose head branch matches `branch`, including merged/closed PRs so stale
+ * topic snapshots can refresh lifecycle state after GitHub changes outside the
+ * app. Returns `status: 'gh-missing'` when `gh` is unavailable / not authed.
*/
export const getLinkedPullRequest = async (payload: {
branch: string;
path: string;
+ pullRequestNumber?: number;
}): Promise<GitLinkedPullRequestResult> => {
- const { path: dirPath, branch } = payload;
- if (!branch) return { pullRequest: null, status: 'ok' };
+ const { path: dirPath, branch, pullRequestNumber } = payload;
+ if (!branch && pullRequestNumber === undefined) return { pullRequest: null, status: 'ok' };
try {
+ if (pullRequestNumber !== undefined) {
+ const { stdout } = await execFileAsync(
+ 'gh',
+ ['pr', 'view', String(pullRequestNumber), '--json', GITHUB_PULL_REQUEST_FIELDS],
+ { cwd: dirPath, timeout: 8000 },
+ );
+ const parsed = JSON.parse(stdout.trim() || '{}') as GithubPullRequestPayload;
+ return { pullRequest: normalizeGithubPullRequest(parsed), status: 'ok' };
+ }
+
const { stdout } = await execFileAsync(
'gh',
[
@@ -151,11 +167,11 @@ export const getLinkedPullRequest = async (payload: {
'--head',
branch,
'--state',
- 'open',
+ 'all',
'--limit',
'5',
'--json',
- 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup',
+ GITHUB_PULL_REQUEST_FIELDS,
],
{ cwd: dirPath, timeout: 8000 },
);
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index 435c185b923..af484c83ebf 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -22,9 +22,9 @@ export interface GitLinkedPullRequest {
export type GitLinkedPullRequestLookupStatus = 'ok' | 'gh-missing' | 'error';
export interface GitLinkedPullRequestResult {
- /** Additional open PRs targeting the same head branch, beyond the primary one. */
+ /** Additional PRs targeting the same head branch, beyond the primary one. */
extraCount?: number;
- /** Null when no open PR is linked to the branch. */
+ /** Null when no PR is linked to the branch. */
pullRequest: GitLinkedPullRequest | null;
/** 'ok' β€” succeeded; 'gh-missing' β€” gh CLI unavailable / not authed; 'error' β€” other. */
status: GitLinkedPullRequestLookupStatus;
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 40889d3df33..49828a927a6 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -85,7 +85,7 @@ export interface DeviceGitLinkedPullRequest {
export type DeviceGitLinkedPullRequestLookupStatus = 'error' | 'gh-missing' | 'ok';
export interface WorkingDirGithubState {
- /** Additional open PRs targeting the same head branch, beyond the primary one. */
+ /** Additional PRs targeting the same head branch, beyond the primary one. */
extraPullRequestCount?: number;
/** GitHub PR linked to the effective working directory's branch. */
pullRequest?: DeviceGitLinkedPullRequest | null;
@@ -269,9 +269,9 @@ export interface DeviceGitBranchInfo {
* (when the repo is a GitHub remote). Mirrors the desktop shape.
*/
export interface DeviceGitLinkedPullRequestResult {
- /** Additional open PRs targeting the same head branch, beyond the primary one. */
+ /** Additional PRs targeting the same head branch, beyond the primary one. */
extraCount?: number;
- /** Null when no open PR is linked to the branch. */
+ /** Null when no PR is linked to the branch. */
pullRequest: DeviceGitLinkedPullRequest | null;
/** 'ok' β€” lookup succeeded; 'gh-missing' β€” gh CLI unavailable; 'error' β€” other failure. */
status: DeviceGitLinkedPullRequestLookupStatus;
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index a6e0fdeffe2..24ebab870be 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -466,12 +466,16 @@ export const deviceKeys = {
deviceId,
path,
]),
- gitLinkedPR: def('device:gitLinkedPR', (deviceId: string, path: string, branch: string) => [
+ gitLinkedPR: def(
'device:gitLinkedPR',
- deviceId,
- path,
- branch,
- ]),
+ (deviceId: string, path: string, branch: string, pullRequestNumber?: number) => [
+ 'device:gitLinkedPR',
+ deviceId,
+ path,
+ branch,
+ ...(pullRequestNumber === undefined ? [] : [pullRequestNumber]),
+ ],
+ ),
gitRemoteBranches: def('device:gitRemoteBranches', (deviceId: string, dirPath: string) => [
'device:gitRemoteBranches',
deviceId,
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
index 920ae291d9a..e72725a5b8b 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
@@ -8,6 +8,7 @@ import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
const getSearchSuffix = (searchParams: URLSearchParams) => {
const search = searchParams.toString();
@@ -24,10 +25,16 @@ const ChatHydration = memo(() => {
const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });
const routeTopicId = params.topicId;
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
+ const topicMetadata = useChatStore((s) =>
+ routeTopicId ? topicSelectors.getTopicById(routeTopicId)(s)?.metadata : undefined,
+ );
+ const useFetchTopicLinkedPullRequest = useChatStore((s) => s.useFetchTopicLinkedPullRequest);
// Route hydration sets activeTopicId directly (below) instead of going through
// switchTopic, so clear any lingering persisted unread once the topic loads.
useClearActiveTopicUnread();
+ useFetchTopicLinkedPullRequest(activeAgentId ? routeTopicId : undefined, topicMetadata);
useLayoutEffect(() => {
const target = routeTopicId ?? null;
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 8488f7b5523..1dd6b7b9049 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -43,6 +43,7 @@ class ElectronGitService {
async getLinkedPullRequest(params: {
branch: string;
path: string;
+ pullRequestNumber?: number;
}): Promise<GitLinkedPullRequestResult> {
return this.ipc.git.getLinkedPullRequest(params);
}
diff --git a/src/services/git.ts b/src/services/git.ts
index bbc530992b3..712ec63596b 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -192,20 +192,28 @@ class GitService {
/**
* PR linked to `branch` on a GitHub repo. Shells out to `gh pr list` (8s
* timeout), so callers throttle this far more aggressively than the branch
- * read. Returns `undefined` when nothing is linked / the lookup is skipped.
+ * read. Includes merged/closed PRs so persisted snapshots can refresh after
+ * GitHub changes outside the app.
*/
async getLinkedPullRequest({
branch,
deviceId,
path,
+ pullRequestNumber,
}: {
branch: string;
deviceId?: string;
path: string;
+ pullRequestNumber?: number;
}): Promise<GitLinkedPRSummary | undefined> {
const pr = deviceId
- ? await lambdaClient.device.gitLinkedPullRequest.query({ branch, deviceId, path })
- : await electronGitService.getLinkedPullRequest({ branch, path });
+ ? await lambdaClient.device.gitLinkedPullRequest.query({
+ branch,
+ deviceId,
+ path,
+ pullRequestNumber,
+ })
+ : await electronGitService.getLinkedPullRequest({ branch, path, pullRequestNumber });
if (!pr) return undefined;
return {
extraCount: pr.extraCount,
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
index 3dc49b46968..0b2f1398b67 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
@@ -1,16 +1,16 @@
-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 { gitService } from '@/services/git';
import type { ChatStore } from '@/store/chat/store';
+import {
+ canReadTopicGitTransport,
+ mergeWorkingDirGithubState,
+ resolveTopicGitTransport,
+ toWorkingDirGithubState,
+} from '@/store/chat/utils/topicWorkingDirGit';
import { deviceSelectors, getDeviceStoreState } from '@/store/device';
-import { getElectronStoreState } from '@/store/electron';
import { topicSelectors } from '../../../topic/selectors';
@@ -37,16 +37,6 @@ const resolveRepoType = async (params: {
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.
@@ -73,16 +63,11 @@ export const snapshotTopicWorkingDirGit = async (
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;
+ const { deviceId, isLocalDevice, targetDeviceId } = resolveTopicGitTransport(agentId);
// 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;
+ if (!canReadTopicGitTransport({ deviceId })) 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
@@ -99,27 +84,15 @@ export const snapshotTopicWorkingDirGit = async (
if (!branch || detached) return;
const prData = await gitService.getLinkedPullRequest({ branch, deviceId, path });
- const github = toGithubMetadata(prData);
+ const github = toWorkingDirGithubState(prData);
if (!github) return;
- const source = currentConfig?.path ?? path;
- const isWorktree = source !== path;
- const git: NonNullable<WorkingDirConfig['git']> = {
- ...currentConfig?.git,
+ const nextConfig = mergeWorkingDirGithubState({
branch,
+ currentConfig,
github,
- isWorktree,
- };
- delete git.detached;
- if (isWorktree) git.activeWorktree = path;
- else delete git.activeWorktree;
-
- const nextConfig: WorkingDirConfig = {
- ...currentConfig,
- git,
- path: source,
- repoType: 'github',
- };
+ path,
+ });
if (isEqual(currentConfig, nextConfig)) return;
await get().updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 35215c7e4d4..227e2257d9f 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -1476,7 +1476,6 @@ describe('topic action', () => {
expect(useChatStore.getState().topicLoadingIdCounts[topicId]).toBeUndefined();
});
});
-
describe('cleanupStaleRunningTopics', () => {
it('should mark stale running topics active when no alive operation exists', async () => {
const { result } = renderHook(() => useChatStore());
@@ -1709,6 +1708,169 @@ describe('topic action', () => {
expect(topicService.updateTopic).not.toHaveBeenCalledWith(topicId, { status: 'active' });
});
});
+
+ describe('internal_updateTopicLinkedPullRequest', () => {
+ const agentId = 'agent-1';
+ const topicId = 'topic-1';
+ const branch = 'fix/topic-running';
+ const path = '/repo';
+ const key = topicMapKey({ agentId });
+ const stalePR = {
+ number: 123,
+ state: 'OPEN',
+ title: 'fix: stop stale running topics',
+ url: 'https://github.com/lobehub/lobehub/pull/123',
+ };
+ const mergedPR = {
+ ...stalePR,
+ mergedAt: '2026-07-07T09:00:00Z',
+ state: 'MERGED',
+ };
+
+ const setupTopic = (
+ pullRequest: typeof stalePR | null = stalePR,
+ pullRequestStatus: 'error' | 'gh-missing' | 'ok' = 'ok',
+ ) => {
+ const topic: ChatTopic = {
+ createdAt: Date.now(),
+ favorite: false,
+ id: topicId,
+ metadata: {
+ workingDirectory: path,
+ workingDirectoryConfig: {
+ git: {
+ branch,
+ github: { pullRequest, pullRequestStatus },
+ isWorktree: false,
+ },
+ path,
+ repoType: 'github',
+ },
+ },
+ sessionId: agentId,
+ title: 'Topic',
+ updatedAt: Date.now(),
+ };
+
+ useChatStore.setState({
+ activeAgentId: agentId,
+ topicDataMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [topic],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ topicLoadingIdCounts: {},
+ topicLoadingIds: [],
+ });
+ };
+
+ it('silently patches the topic with the latest merged PR state', async () => {
+ const { result } = renderHook(() => useChatStore());
+ setupTopic();
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue(undefined as never);
+
+ await act(async () => {
+ await result.current.internal_updateTopicLinkedPullRequest(
+ { branch, path, pullRequestNumber: 123, topicId },
+ { pullRequest: mergedPR, pullRequestStatus: 'ok' },
+ );
+ });
+
+ const updatedTopic = useChatStore.getState().topicDataMap[key]!.items[0]!;
+ expect(updatedTopic.metadata?.workingDirectoryConfig?.git?.github).toEqual({
+ pullRequest: mergedPR,
+ pullRequestStatus: 'ok',
+ });
+ expect(updateTopicMetadataMock).toHaveBeenCalledWith(topicId, {
+ workingDirectoryConfig: {
+ git: {
+ branch,
+ github: { pullRequest: mergedPR, pullRequestStatus: 'ok' },
+ isWorktree: false,
+ },
+ path,
+ repoType: 'github',
+ },
+ });
+ expect(useChatStore.getState().topicLoadingIds).toEqual([]);
+ });
+
+ it('updates empty PR metadata when no existing PR number is anchored', async () => {
+ const { result } = renderHook(() => useChatStore());
+ setupTopic(null, 'error');
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue(undefined as never);
+
+ await act(async () => {
+ await result.current.internal_updateTopicLinkedPullRequest(
+ { branch, path, topicId },
+ { pullRequest: null, pullRequestStatus: 'ok' },
+ );
+ });
+
+ expect(
+ useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git
+ ?.github,
+ ).toEqual({ pullRequest: null, pullRequestStatus: 'ok' });
+ expect(updateTopicMetadataMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the existing PR snapshot when lookup returns a different PR number', async () => {
+ const { result } = renderHook(() => useChatStore());
+ setupTopic();
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue(undefined as never);
+
+ await act(async () => {
+ await result.current.internal_updateTopicLinkedPullRequest(
+ { branch, path, pullRequestNumber: 123, topicId },
+ {
+ pullRequest: {
+ ...mergedPR,
+ number: 456,
+ url: 'https://github.com/lobehub/lobehub/pull/456',
+ },
+ pullRequestStatus: 'ok',
+ },
+ );
+ });
+
+ expect(updateTopicMetadataMock).not.toHaveBeenCalled();
+ expect(
+ useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git
+ ?.github,
+ ).toEqual({ pullRequest: stalePR, pullRequestStatus: 'ok' });
+ });
+
+ it('keeps the existing PR snapshot when gh is unavailable', async () => {
+ const { result } = renderHook(() => useChatStore());
+ setupTopic();
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue(undefined as never);
+
+ await act(async () => {
+ await result.current.internal_updateTopicLinkedPullRequest(
+ { branch, path, topicId },
+ { ghMissing: true, pullRequest: null, pullRequestStatus: 'gh-missing' },
+ );
+ });
+
+ expect(updateTopicMetadataMock).not.toHaveBeenCalled();
+ expect(
+ useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git
+ ?.github,
+ ).toEqual({ pullRequest: stalePR, pullRequestStatus: 'ok' });
+ });
+ });
describe('updateTopicLoading', () => {
it('should call update topicLoadingId', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 8df7964758b..6bb00169c61 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -11,13 +11,22 @@ import useSWR from 'swr';
import { message } from '@/components/AntdStaticMethods';
import { LOADING_FLAT } from '@/const/message';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
-import { cronKeys, topicKeys } from '@/libs/swr/keys';
+import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';
import { chatService } from '@/services/chat';
+import { type GitLinkedPRSummary, gitService } from '@/services/git';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat';
import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { topicMapKey, type TopicMapScope } from '@/store/chat/utils/topicMapKey';
+import {
+ canReadTopicGitTransport,
+ getTopicLinkedPullRequestBase,
+ isSuccessfulLinkedPullRequestLookup,
+ mergeWorkingDirGithubState,
+ resolveTopicGitTransport,
+ toWorkingDirGithubState,
+} from '@/store/chat/utils/topicWorkingDirGit';
import { useGlobalStore } from '@/store/global';
import { getHomeStoreState } from '@/store/home';
import { type StoreSetter } from '@/store/types';
@@ -84,6 +93,15 @@ export interface SwitchTopicOptions {
}
type Setter = StoreSetter<ChatStore>;
+
+interface TopicLinkedPullRequestRefreshParams {
+ branch: string;
+ deviceId?: string;
+ path: string;
+ pullRequestNumber?: number;
+ topicId: string;
+}
+
export const chatTopic = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new ChatTopicActionImpl(set, get, _api);
@@ -105,6 +123,29 @@ export class ChatTopicActionImpl {
this.#get = get;
}
+ #resolveTopicLinkedPullRequestRefreshParams = (
+ topicId: string,
+ metadata?: ChatTopicMetadata,
+ ): TopicLinkedPullRequestRefreshParams | undefined => {
+ const sourceMetadata = metadata ?? topicSelectors.getTopicById(topicId)(this.#get())?.metadata;
+ const base = getTopicLinkedPullRequestBase(sourceMetadata);
+ if (!base) return undefined;
+
+ const { activeAgentId } = this.#get();
+ if (!activeAgentId) return undefined;
+
+ const transport = resolveTopicGitTransport(activeAgentId);
+ if (!canReadTopicGitTransport(transport)) return undefined;
+
+ return {
+ branch: base.branch,
+ deviceId: transport.deviceId,
+ path: base.path,
+ pullRequestNumber: base.pullRequestNumber,
+ topicId,
+ };
+ };
+
closeAllTopicsDrawer = (): void => {
this.#set({ allTopicsDrawerOpen: false }, false, n('closeAllTopicsDrawer'));
};
@@ -559,6 +600,50 @@ export class ChatTopicActionImpl {
}
};
+ useFetchTopicLinkedPullRequest = (
+ topicId?: string,
+ metadata?: ChatTopicMetadata,
+ ): SWRResponse<GitLinkedPRSummary | undefined> => {
+ const params = topicId
+ ? this.#resolveTopicLinkedPullRequestRefreshParams(topicId, metadata)
+ : undefined;
+
+ return useClientDataSWRWithSync<GitLinkedPRSummary | undefined>(
+ params
+ ? deviceKeys.gitLinkedPR(
+ params.deviceId ?? 'local',
+ params.path,
+ params.branch,
+ params.pullRequestNumber,
+ )
+ : null,
+ params
+ ? () =>
+ gitService.getLinkedPullRequest({
+ branch: params.branch,
+ deviceId: params.deviceId,
+ path: params.path,
+ pullRequestNumber: params.pullRequestNumber,
+ })
+ : null,
+ {
+ dedupingInterval: 60 * 1000,
+ focusThrottleInterval: 60 * 1000,
+ onData: (prData) => {
+ if (!params) return;
+
+ void this.#get()
+ .internal_updateTopicLinkedPullRequest(params, prData)
+ .catch((error) => {
+ console.error('[useFetchTopicLinkedPullRequest] sync failed:', error);
+ });
+ },
+ revalidateOnFocus: true,
+ shouldRetryOnError: false,
+ },
+ );
+ };
+
autoRenameTopicTitle = async (id: string): Promise<void> => {
const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = this.#get();
@@ -1281,6 +1366,69 @@ export class ChatTopicActionImpl {
}
};
+ internal_updateTopicLinkedPullRequest = async (
+ params: TopicLinkedPullRequestRefreshParams,
+ prData?: GitLinkedPRSummary,
+ ): Promise<void> => {
+ if (!isSuccessfulLinkedPullRequestLookup(prData)) return;
+
+ const topic = topicSelectors.getTopicById(params.topicId)(this.#get());
+ if (!topic) return;
+
+ const base = getTopicLinkedPullRequestBase(topic.metadata);
+ if (
+ !base ||
+ base.branch !== params.branch ||
+ base.path !== params.path ||
+ base.pullRequestNumber !== params.pullRequestNumber
+ ) {
+ return;
+ }
+
+ const github = toWorkingDirGithubState(prData);
+ if (!github) return;
+
+ if (
+ base.pullRequestNumber !== undefined &&
+ github.pullRequest?.number !== base.pullRequestNumber
+ ) {
+ return;
+ }
+
+ const nextConfig = mergeWorkingDirGithubState({
+ branch: base.branch,
+ currentConfig: base.currentConfig,
+ github,
+ path: base.path,
+ });
+
+ if (isEqual(base.currentConfig, nextConfig)) return;
+
+ this.#get().internal_dispatchTopic(
+ {
+ id: params.topicId,
+ type: 'updateTopic',
+ value: {
+ metadata: {
+ ...topic.metadata,
+ workingDirectoryConfig: nextConfig,
+ },
+ },
+ },
+ n('refreshTopicLinkedPullRequest'),
+ );
+
+ try {
+ await topicService.updateTopicMetadata(params.topicId, {
+ workingDirectoryConfig: nextConfig,
+ });
+ await this.#get().refreshTopic();
+ } catch (error) {
+ await this.#get().refreshTopic();
+ throw error;
+ }
+ };
+
internal_createTopic = async (params: CreateTopicParams): Promise<string> => {
const tmpId = Date.now().toString();
this.#get().internal_dispatchTopic(
diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.ts
new file mode 100644
index 00000000000..e000f2bd568
--- /dev/null
+++ b/src/store/chat/utils/topicWorkingDirGit.ts
@@ -0,0 +1,110 @@
+import { isDesktop } from '@lobechat/const';
+import type { ChatTopicMetadata, WorkingDirConfig, WorkingDirGithubState } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
+
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
+import type { GitLinkedPRSummary } from '@/services/git';
+import { getAgentStoreState } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { getElectronStoreState } from '@/store/electron';
+
+export interface TopicGitTransport {
+ deviceId?: string;
+ isLocalDevice: boolean;
+ targetDeviceId?: string;
+}
+
+export interface TopicLinkedPullRequestBase {
+ branch: string;
+ currentConfig?: WorkingDirConfig;
+ path: string;
+ pullRequestNumber?: number;
+}
+
+export const canReadTopicGitTransport = (transport: Pick<TopicGitTransport, 'deviceId'>) =>
+ !!transport.deviceId || isDesktop;
+
+export const resolveTopicGitTransport = (agentId: string): TopicGitTransport => {
+ 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;
+
+ return {
+ deviceId: isLocalDevice ? undefined : targetDeviceId,
+ isLocalDevice,
+ targetDeviceId,
+ };
+};
+
+export const getTopicLinkedPullRequestBase = (
+ metadata?: ChatTopicMetadata,
+): TopicLinkedPullRequestBase | undefined => {
+ const currentConfig = metadata?.workingDirectoryConfig;
+ const git = currentConfig?.git;
+ const branch = git?.branch;
+ const path = getWorkingDirEffectivePath(currentConfig) ?? metadata?.workingDirectory;
+ const repoType =
+ currentConfig?.repoType ??
+ (git?.github ? 'github' : undefined) ??
+ (isDesktop ? undefined : 'github');
+
+ if (!path || !branch || git?.detached || repoType !== 'github') return undefined;
+
+ return {
+ branch,
+ currentConfig,
+ path,
+ pullRequestNumber: git?.github?.pullRequest?.number,
+ };
+};
+
+export const isSuccessfulLinkedPullRequestLookup = (
+ prData?: GitLinkedPRSummary,
+): prData is GitLinkedPRSummary =>
+ !!prData && !prData.ghMissing && (prData.pullRequestStatus ?? 'ok') === 'ok';
+
+export const toWorkingDirGithubState = (
+ 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'),
+ };
+};
+
+export const mergeWorkingDirGithubState = ({
+ branch,
+ currentConfig,
+ github,
+ path,
+}: {
+ branch: string;
+ currentConfig?: WorkingDirConfig;
+ github: WorkingDirGithubState;
+ path: string;
+}): WorkingDirConfig => {
+ 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;
+
+ return {
+ ...currentConfig,
+ git,
+ path: source,
+ repoType: 'github',
+ };
+};
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 0ef521ffb89..c3bfbe4ac21 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -147,7 +147,8 @@ export const useFetchGitBranch = (deviceId: string | undefined, path?: string) =
* so keep a long 60s dedupe + 60s focus throttle β€” unlike the cheap branch read,
* this must NOT re-run on every remount or directory revisit. Keyed by branch,
* so a checkout naturally re-keys into a fresh lookup; disabled for non-github
- * repos and detached HEAD (no branch ref to query).
+ * repos and detached HEAD (no branch ref to query). Includes merged/closed PRs
+ * so the lifecycle badge can refresh after GitHub changes outside the app.
*/
export const useFetchGitLinkedPR = (
deviceId: string | undefined,