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(coding): link a topic's pull requests only from agent commands, several per topic (#23185)

Bryanbfe6c91954e0
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index 2d8e5463593..8bf8246f585 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -17,7 +17,12 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createCanvasStorageService, isOwnCanvasManifestKey } from '@/server/services/canvas';
import { deleteCanvas } from '@/server/services/canvas/delete';
-import { registerShellWorksForLocalRun } from '@/server/services/workRegistration';
+import {
+ linkPushedPullRequests,
+ listTopicPullRequestsWithStatus,
+ registerShellWorksForLocalRun,
+ resolveShellPullRequestLinking,
+} from '@/server/services/workRegistration';
const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -272,8 +277,64 @@ export const workRouter = router({
anchorMessageId: input.anchorMessageId,
messageIds: input.messageIds,
messageModel: ctx.messageModel,
+ pullRequestLinking: await resolveShellPullRequestLinking({
+ db: ctx.serverDB,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ workModel: ctx.workModel,
+ workspaceId: ctx.workspaceId,
+ }),
+ topicId: input.topicId,
+ workModel: ctx.workModel,
+ }),
+ ),
+
+ // Better Coding Experience: the GitHub pull requests a topic's Work rows
+ // link, with the GitHub App's state where an installation tracks the repo.
+ listTopicPullRequests: workProcedure
+ .input(z.object({ topicId: z.string().min(1) }))
+ .query(async ({ ctx, input }) =>
+ listTopicPullRequestsWithStatus({
+ db: ctx.serverDB,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ workModel: ctx.workModel,
+ workspaceId: ctx.workspaceId,
+ }),
+ ),
+
+ // Better Coding Experience: link the pull requests a `git push` tool call
+ // updated, right after it ran. The push itself is re-read from the persisted
+ // tool message; see `linkPushedPullRequests` for what the device may add.
+ linkPushedPullRequests: skillWorkProcedureWrite
+ .input(
+ z.object({
+ pullRequests: z
+ .array(
+ z.object({
+ headRefName: z.string().min(1).max(255),
+ isDraft: z.boolean().optional(),
+ number: z.number().int().positive(),
+ state: z.string().max(32).optional(),
+ title: z.string().max(1024).optional(),
+ url: z.string().url().max(2048),
+ }),
+ )
+ .max(10),
+ toolCallId: z.string().min(1).max(255),
+ topicId: z.string().min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) =>
+ linkPushedPullRequests({
+ db: ctx.serverDB,
+ devicePullRequests: input.pullRequests,
+ messageModel: ctx.messageModel,
+ toolCallId: input.toolCallId,
topicId: input.topicId,
+ userId: ctx.userId,
workModel: ctx.workModel,
+ workspaceId: ctx.workspaceId,
}),
),
});
diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.ts
index d10a494fc2b..8caa90e56a1 100644
--- a/apps/server/src/services/workRegistration/index.ts
+++ b/apps/server/src/services/workRegistration/index.ts
@@ -21,6 +21,11 @@ export {
type LocalRunShellWorksResult,
registerShellWorksForLocalRun,
} from './localRunWorkRegistration';
+export {
+ isBetterCodingExperienceEnabled,
+ resolveShellPullRequestLinking,
+ type ShellPullRequestLinking,
+} from './pullRequestLinking';
export {
registerWorksForOperation,
type RegisterWorksForOperationParams,
@@ -28,3 +33,9 @@ export {
} from './registerWorksForOperation';
export { resolveRunWorkAccessScope, type ShareVisitorWorkIdentity } from './shareWorkScope';
export { stateHasEntityFileEdits } from './stateHasEntityFileEdits';
+export {
+ type DeviceReportedPullRequest,
+ linkPushedPullRequests,
+ type LinkPushedPullRequestsResult,
+ listTopicPullRequestsWithStatus,
+} from './topicPullRequests';
diff --git a/apps/server/src/services/workRegistration/localRunWorkRegistration.ts b/apps/server/src/services/workRegistration/localRunWorkRegistration.ts
index e618d473951..15e7e76b63c 100644
--- a/apps/server/src/services/workRegistration/localRunWorkRegistration.ts
+++ b/apps/server/src/services/workRegistration/localRunWorkRegistration.ts
@@ -4,6 +4,7 @@ import type { MessageModel } from '@/database/models/message';
import type { WorkModel } from '@/database/models/work';
import { UNEXECUTED_INTERVENTION_STATUSES } from './constants';
+import type { ShellPullRequestLinking } from './pullRequestLinking';
import { registerShellWorks } from './shellWorkRegistration';
const log = debug('lobe-server:local-run-work-registration');
@@ -53,10 +54,13 @@ export const registerShellWorksForLocalRun = async (params: {
anchorMessageId: string;
messageIds: string[];
messageModel: MessageModel;
+ /** Better Coding Experience pull request linking; see `registerShellWorks`. */
+ pullRequestLinking?: ShellPullRequestLinking;
topicId: string;
workModel: WorkModel;
}): Promise<LocalRunShellWorksResult> => {
- const { anchorMessageId, messageIds, messageModel, topicId, workModel } = params;
+ const { anchorMessageId, messageIds, messageModel, pullRequestLinking, topicId, workModel } =
+ params;
const anchor = await messageModel.findById(anchorMessageId);
// The anchor must be an assistant message of the claimed topic — anything
@@ -95,6 +99,7 @@ export const registerShellWorksForLocalRun = async (params: {
cumulativeCost: null,
cumulativeUsage: null,
operationId: rootOperationId,
+ pullRequestLinking,
records,
threadId: anchor.threadId,
topicId,
diff --git a/apps/server/src/services/workRegistration/pullRequestLinking.test.ts b/apps/server/src/services/workRegistration/pullRequestLinking.test.ts
new file mode 100644
index 00000000000..dab1c84959e
--- /dev/null
+++ b/apps/server/src/services/workRegistration/pullRequestLinking.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createShellPullRequestLinking } from './pullRequestLinking';
+
+vi.mock('@/database/models/scm', () => ({
+ ScmChangeRequestModel: { listOpenByHeadRefs: vi.fn() },
+}));
+vi.mock('@/database/models/user', () => ({ UserModel: vi.fn() }));
+
+describe('createShellPullRequestLinking', () => {
+ it('re-reads the topic pull requests for each command, so a PR linked earlier in the run resolves', async () => {
+ const listTopicPullRequests = vi
+ .fn()
+ .mockResolvedValueOnce([{ identifier: 'a/b#1' }])
+ .mockResolvedValueOnce([{ identifier: 'a/b#2' }, { identifier: 'a/b#1' }]);
+ const linking = createShellPullRequestLinking({
+ db: {} as any,
+ topicId: 't1',
+ userId: 'u1',
+ workModel: { listTopicPullRequests } as any,
+ });
+
+ expect(await linking.listTopicPullRequestIds()).toEqual(['a/b#1']);
+ // `gh pr create` then registered a/b#2; the next bare `gh pr merge 2` must see it.
+ expect(await linking.listTopicPullRequestIds()).toEqual(['a/b#2', 'a/b#1']);
+ expect(listTopicPullRequests).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/server/src/services/workRegistration/pullRequestLinking.ts b/apps/server/src/services/workRegistration/pullRequestLinking.ts
new file mode 100644
index 00000000000..5d9a0749c0d
--- /dev/null
+++ b/apps/server/src/services/workRegistration/pullRequestLinking.ts
@@ -0,0 +1,93 @@
+import debug from 'debug';
+
+import { ScmChangeRequestModel } from '@/database/models/scm';
+import { UserModel } from '@/database/models/user';
+import type { WorkModel } from '@/database/models/work';
+import type { LobeChatDatabase } from '@/database/type';
+
+const log = debug('lobe-server:pull-request-linking');
+
+/** A pull request a `git push` updated, as the GitHub App last reported it. */
+export interface PushedPullRequest {
+ headRef: string | null;
+ number: number;
+ repoFullName: string;
+ title: string | null;
+ url: string;
+}
+
+/**
+ * What the shell Work scan needs to tie pull requests to a topic beyond
+ * `gh pr create|edit` (Better Coding Experience). Present only while the lab
+ * is on for the run's user, so a scan without it behaves exactly as before.
+ */
+export interface ShellPullRequestLinking {
+ /** Open pull requests of `repoFullName` headed by one of `branches`. */
+ findOpenPullRequestsByHead: (
+ repoFullName: string,
+ branches: string[],
+ ) => Promise<PushedPullRequest[]>;
+ /** `owner/repo#n` of every pull request already linked to the topic. */
+ listTopicPullRequestIds: () => Promise<string[]>;
+}
+
+/** `users.preference.lab.enableBetterCodingExperience`, false when unreadable. */
+export const isBetterCodingExperienceEnabled = async (
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<boolean> => {
+ try {
+ const preference = await new UserModel(db, userId).getUserPreference();
+ return preference?.lab?.enableBetterCodingExperience === true;
+ } catch (error) {
+ log('Failed to read the Better Coding Experience preference: %O', error);
+ return false;
+ }
+};
+
+/**
+ * Pull request lookups for one topic's scan. The push lookup reads
+ * `scm_change_requests` — the GitHub App's webhook-fed rows — under the same
+ * visibility as the SCM settings list, so a push only ever links pull
+ * requests the scope can already see. Without an installation tracking the
+ * repository it finds nothing, and the client's device lookup takes over.
+ */
+export const createShellPullRequestLinking = (params: {
+ db: LobeChatDatabase;
+ topicId: string;
+ userId: string;
+ workModel: WorkModel;
+ workspaceId?: string | null;
+}): ShellPullRequestLinking => {
+ const scope = { userId: params.userId, workspaceId: params.workspaceId ?? null };
+
+ return {
+ findOpenPullRequestsByHead: async (repoFullName, branches) => {
+ const rows = await ScmChangeRequestModel.listOpenByHeadRefs(
+ params.db,
+ scope,
+ repoFullName,
+ branches,
+ );
+ return rows.map((row) => ({
+ headRef: row.headRef,
+ number: row.number,
+ repoFullName: row.repoFullName,
+ title: row.title,
+ url: row.url,
+ }));
+ },
+ // Read per command, never cached for the scan: an earlier record of the same
+ // run may just have linked the PR a later bare `gh pr merge <n>` names.
+ listTopicPullRequestIds: async () =>
+ (await params.workModel.listTopicPullRequests(params.topicId)).map((item) => item.identifier),
+ };
+};
+
+/** {@link createShellPullRequestLinking} when the lab is on for `userId`, else undefined. */
+export const resolveShellPullRequestLinking = async (
+ params: Parameters<typeof createShellPullRequestLinking>[0],
+): Promise<ShellPullRequestLinking | undefined> =>
+ (await isBetterCodingExperienceEnabled(params.db, params.userId))
+ ? createShellPullRequestLinking(params)
+ : undefined;
diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.ts
index 6cdad3b0af5..b6ff2974d1f 100644
--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts
+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts
@@ -23,6 +23,7 @@ import { MarketService } from '@/server/services/market';
import { createSandboxService } from '@/server/services/sandbox';
import { UNEXECUTED_INTERVENTION_STATUSES } from './constants';
+import { resolveShellPullRequestLinking } from './pullRequestLinking';
import { resolveRunWorkAccessScope, type ShareVisitorWorkIdentity } from './shareWorkScope';
import { registerShellWorks } from './shellWorkRegistration';
@@ -428,11 +429,23 @@ export const registerWorksForOperation = async (
// counted, never thrown. Unlike file Works there is no device-provenance
// objection: the registered entities are REMOTE resources whose identity/url
// is independent of where the CLI ran.
+ // A share visitor's run is fenced off from the creator's topics, so it never
+ // links pull requests into them.
+ const pullRequestLinking = params.agentShareVisitor
+ ? undefined
+ : await resolveShellPullRequestLinking({
+ db: serverDB,
+ topicId,
+ userId,
+ workModel,
+ workspaceId,
+ });
const shellOutcome = await registerShellWorks({
agentId: completingOp.agentId,
cumulativeCost,
cumulativeUsage,
operationId,
+ pullRequestLinking,
records,
threadId: completingOp.threadId,
topicId,
diff --git a/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts b/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts
new file mode 100644
index 00000000000..15d734a71a7
--- /dev/null
+++ b/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts
@@ -0,0 +1,172 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ShellPullRequestLinking } from './pullRequestLinking';
+import { registerShellWorks, type ShellWorkScanRecord } from './shellWorkRegistration';
+
+/** A claude-code Bash row: its stdout + stderr arrive as the message body. */
+const bashRow = (id: string, command: string, content: string): ShellWorkScanRecord => ({
+ apiName: 'Bash',
+ arguments: JSON.stringify({ command }),
+ content,
+ id,
+ identifier: 'claude-code',
+ toolCallId: `call-${id}`,
+});
+
+const PUSH_OUTPUT = [
+ 'To github.com:lobehub/lobehub.git',
+ ' 031bf96..f6b1c2a feat/x -> feat/x',
+].join('\n');
+
+const createWorkModel = () =>
+ ({
+ registerExternal: vi.fn(async (params: { resourceId: string }) => ({ id: params.resourceId })),
+ registerShellGithubResult: vi.fn(async () => ({ id: 'wk-gh' })),
+ }) as any;
+
+const createLinking = (overrides: Partial<ShellPullRequestLinking> = {}) => ({
+ findOpenPullRequestsByHead: vi.fn(async () => [
+ {
+ headRef: 'feat/x',
+ number: 12,
+ repoFullName: 'lobehub/lobehub',
+ title: 'Feat X',
+ url: 'https://github.com/lobehub/lobehub/pull/12',
+ },
+ ]),
+ listTopicPullRequestIds: vi.fn(async () => ['lobehub/lobehub#12']),
+ ...overrides,
+});
+
+const scan = (
+ records: ShellWorkScanRecord[],
+ workModel: any,
+ pullRequestLinking?: ShellPullRequestLinking,
+) =>
+ registerShellWorks({
+ cumulativeCost: null,
+ cumulativeUsage: null,
+ operationId: 'op-1',
+ pullRequestLinking,
+ records,
+ topicId: 'topic-1',
+ workModel,
+ });
+
+describe('registerShellWorks · pull request linking', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('leaves pushes and lifecycle commands alone while the lab is off', async () => {
+ const workModel = createWorkModel();
+
+ await scan(
+ [bashRow('m1', 'git push', PUSH_OUTPUT), bashRow('m2', 'gh pr merge 12 --squash', '')],
+ workModel,
+ );
+
+ expect(workModel.registerExternal).not.toHaveBeenCalled();
+ // The gh scanner still runs, exactly as before: no lifecycle option.
+ expect(workModel.registerShellGithubResult).toHaveBeenCalledTimes(1);
+ expect(workModel.registerShellGithubResult.mock.calls[0]).toHaveLength(1);
+ });
+
+ it('links the open pull request a push updated, from the push report', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking();
+
+ const outcome = await scan([bashRow('m1', 'git push', PUSH_OUTPUT)], workModel, linking);
+
+ expect(linking.findOpenPullRequestsByHead).toHaveBeenCalledWith('lobehub/lobehub', ['feat/x']);
+ expect(workModel.registerExternal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ changeType: 'updated',
+ messageId: 'm1',
+ metadata: { headBranch: 'feat/x' },
+ patchFields: ['identifier', 'title', 'url'],
+ resourceId: 'lobehub/lobehub#12',
+ resourceType: 'github_pull_request',
+ rootOperationId: 'op-1',
+ toolCallId: 'call-m1',
+ topicId: 'topic-1',
+ }),
+ );
+ expect(outcome).toMatchObject({ attempted: 1, registered: 1 });
+ });
+
+ it('reads the push report from stderr for a device runCommand', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking();
+
+ await scan(
+ [
+ {
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ command: 'git push' }),
+ id: 'm1',
+ identifier: 'lobe-local-system',
+ state: { exitCode: 0, stderr: PUSH_OUTPUT, stdout: 'done' },
+ toolCallId: 'call-m1',
+ },
+ ],
+ workModel,
+ linking,
+ );
+
+ expect(linking.findOpenPullRequestsByHead).toHaveBeenCalledWith('lobehub/lobehub', ['feat/x']);
+ });
+
+ it('links nothing when no tracked pull request heads the pushed branch', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking({ findOpenPullRequestsByHead: vi.fn(async () => []) });
+
+ const outcome = await scan([bashRow('m1', 'git push', PUSH_OUTPUT)], workModel, linking);
+
+ expect(workModel.registerExternal).not.toHaveBeenCalled();
+ expect(outcome).toMatchObject({ attempted: 0, registered: 0 });
+ });
+
+ it('skips a failed push', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking();
+
+ await scan(
+ [{ ...bashRow('m1', 'git push', PUSH_OUTPUT), error: { message: 'rejected' } }],
+ workModel,
+ linking,
+ );
+
+ expect(linking.findOpenPullRequestsByHead).not.toHaveBeenCalled();
+ });
+
+ it('passes the lifecycle option and the topic pull requests to the gh scanner', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking();
+
+ await scan([bashRow('m1', 'gh pr merge 12 --squash', '')], workModel, linking);
+
+ expect(workModel.registerShellGithubResult).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ command: 'gh pr merge 12 --squash' }),
+ }),
+ { pullRequestLifecycle: true, topicPullRequests: ['lobehub/lobehub#12'] },
+ );
+ expect(workModel.registerShellGithubResult.mock.calls[0][0]).not.toHaveProperty('transcript');
+ });
+
+ it('only reads the topic pull requests for a bare ready / merge', async () => {
+ const workModel = createWorkModel();
+ const linking = createLinking();
+
+ await scan(
+ [bashRow('m1', `gh pr create --title t`, 'https://github.com/a/b/pull/1')],
+ workModel,
+ linking,
+ );
+
+ expect(linking.listTopicPullRequestIds).not.toHaveBeenCalled();
+ expect(workModel.registerShellGithubResult).toHaveBeenCalledWith(expect.anything(), {
+ pullRequestLifecycle: true,
+ topicPullRequests: [],
+ });
+ });
+});
diff --git a/apps/server/src/services/workRegistration/shellWorkRegistration.ts b/apps/server/src/services/workRegistration/shellWorkRegistration.ts
index 713f5f5e344..f0d37de5d6c 100644
--- a/apps/server/src/services/workRegistration/shellWorkRegistration.ts
+++ b/apps/server/src/services/workRegistration/shellWorkRegistration.ts
@@ -8,6 +8,7 @@ import debug from 'debug';
import type { WorkModel } from '@/database/models/work';
+import type { ShellPullRequestLinking } from './pullRequestLinking';
import { SHELL_WORK_SCANNERS } from './shellWorkScanners';
const log = debug('lobe-server:shell-work-registration');
@@ -80,6 +81,56 @@ const stringField = (record: Record<string, unknown> | undefined, key: string) =
return typeof value === 'string' && value.length > 0 ? value : undefined;
};
+/**
+ * A shell tool record that ran to success, as the command text plus what it
+ * printed — or null for a non-shell tool, a failed or unexecuted call, or
+ * unparseable arguments. The success gating mirrors fileEditScan.
+ */
+export const readShellCommandRecord = (
+ record: ShellWorkScanRecord,
+): {
+ data: { command: string; exitCode?: number; output?: string };
+ /** Every text the run left, joined; see `ShellWorkScanner` `transcript`. */
+ transcript: string;
+} | null => {
+ if (!record.identifier || SHELL_COMMAND_SOURCES[record.identifier] !== record.apiName)
+ return null;
+ // A plugin-level error means the command never ran / failed (claude-code
+ // is_error rides here); state-level failure signals mirror fileEditScan.
+ if (record.error != null && record.error !== '') return null;
+ const state = isRecord(record.state) ? record.state : undefined;
+ if (state?.success === false) return null;
+ if (state?.error != null && state.error !== '') return null;
+
+ let command: unknown;
+ try {
+ command = JSON.parse(record.arguments ?? '')?.command;
+ } catch {
+ return null;
+ }
+ if (typeof command !== 'string') return null;
+
+ const transcript = [
+ stringField(state, 'stdout'),
+ stringField(state, 'stderr'),
+ stringField(state, 'output'),
+ typeof record.content === 'string' ? record.content : undefined,
+ ]
+ .filter(Boolean)
+ .join('\n');
+
+ return {
+ data: {
+ command,
+ // Absent for claude-code (no exit code is persisted); its failures were
+ // already excluded via the plugin error above.
+ exitCode: typeof state?.exitCode === 'number' ? state.exitCode : undefined,
+ output: stringField(state, 'stdout') ?? stringField(state, 'output') ?? record.content,
+ },
+ transcript,
+ };
+};
+
/**
* Register external Works from the shell tool calls of a completed operation:
* heterogeneous CLI agents (codex / claude-code) and the device
@@ -99,6 +150,11 @@ export const registerShellWorks = async (params: {
cumulativeCost: number | null;
cumulativeUsage: WorkVersionCumulativeUsage | null;
operationId: string;
+ /**
+ * Better Coding Experience pull request linking; omitted (lab off) the scan
+ * registers exactly what it always did.
+ */
+ pullRequestLinking?: ShellPullRequestLinking;
records: ShellWorkScanRecord[];
threadId?: string | null;
topicId: string;
@@ -112,31 +168,13 @@ export const registerShellWorks = async (params: {
};
for (const record of params.records) {
- if (!record.identifier || SHELL_COMMAND_SOURCES[record.identifier] !== record.apiName) continue;
- // A plugin-level error means the command never ran / failed (claude-code
- // is_error rides here); state-level failure signals mirror fileEditScan.
- if (record.error != null && record.error !== '') continue;
- const state = isRecord(record.state) ? record.state : undefined;
- if (state?.success === false) continue;
- if (state?.error != null && state.error !== '') continue;
-
- let command: unknown;
- try {
- command = JSON.parse(record.arguments ?? '')?.command;
- } catch {
- continue;
- }
- if (typeof command !== 'string') continue;
-
- const data = {
- command,
- // Absent for claude-code (no exit code is persisted); its failures were
- // already excluded via the plugin error above.
- exitCode: typeof state?.exitCode === 'number' ? state.exitCode : undefined,
- output: stringField(state, 'stdout') ?? stringField(state, 'output') ?? record.content,
- };
+ const shell = readShellCommandRecord(record);
+ if (!shell) continue;
+ const { data, transcript } = shell;
+ const { command } = data;
for (const scanner of SHELL_WORK_SCANNERS) {
+ if (scanner.requiresPullRequestLinking && !params.pullRequestLinking) continue;
if (!scanner.matches(command)) continue;
try {
@@ -146,15 +184,18 @@ export const registerShellWorks = async (params: {
cumulativeUsage: params.cumulativeUsage,
data,
messageId: record.id,
+ pullRequestLinking: params.pullRequestLinking,
rootOperationId: params.operationId,
threadId: params.threadId ?? null,
toolCallId: record.toolCallId || null,
- toolIdentifier: record.identifier,
+ // Non-null: readShellCommandRecord only accepts known shell sources.
+ toolIdentifier: record.identifier!,
toolName: record.apiName,
topicId: params.topicId,
+ transcript,
workModel: params.workModel,
});
- if (!work) continue;
+ if (!work || (Array.isArray(work) && work.length === 0)) continue;
outcome.attempted += 1;
outcome.registered += 1;
outcome.anchorCandidateMessageId = record.id;
diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/github.ts b/apps/server/src/services/workRegistration/shellWorkScanners/github.ts
index f2738102b62..3a792e3945d 100644
--- a/apps/server/src/services/workRegistration/shellWorkScanners/github.ts
+++ b/apps/server/src/services/workRegistration/shellWorkScanners/github.ts
@@ -1,7 +1,8 @@
import type { ShellWorkScanner } from './types';
/**
- * github issue/PR Works from `gh issue|pr create/edit` runs. Parsing reuses
+ * github issue/PR Works from `gh issue|pr create/edit` runs — plus, under the
+ * Better Coding Experience lab, numbered `gh pr ready|merge` runs. Parsing reuses
* the github skill's gh-CLI normalizer (via
* `workModel.registerShellGithubResult` → `normalizeGithubShellToolResult`),
* so identity lands on the same `owner/repo#number` Work row as
@@ -10,5 +11,15 @@ import type { ShellWorkScanner } from './types';
export const githubShellWorkScanner: ShellWorkScanner = {
matches: (command) => command.includes('gh '),
name: 'github',
- register: ({ workModel, ...input }) => workModel.registerShellGithubResult(input),
+ register: async ({ pullRequestLinking, transcript: _transcript, workModel, ...input }) => {
+ if (!pullRequestLinking) return workModel.registerShellGithubResult(input);
+
+ // A bare `gh pr ready|merge <n>` names no repository; the topic's own
+ // pull requests are the only safe place to look it up.
+ const needsTopic = /\bgh\s+pr\s+(?:ready|merge)\b/.test(input.data.command);
+ return workModel.registerShellGithubResult(input, {
+ pullRequestLifecycle: true,
+ topicPullRequests: needsTopic ? await pullRequestLinking.listTopicPullRequestIds() : [],
+ });
+ },
};
diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts
new file mode 100644
index 00000000000..cbaa9556b8d
--- /dev/null
+++ b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts
@@ -0,0 +1,57 @@
+import { parseGitPushResult } from '@/database/models/work';
+
+import type { ShellWorkScanner } from './types';
+
+/**
+ * A `git push` to a branch that already has an open pull request links that
+ * pull request to the topic (Better Coding Experience only). The branch and
+ * repository come from git's own push report; which pull request the branch
+ * heads comes from the GitHub App's rows — never from the agent's text — so a
+ * push links nothing in a repository no installation tracks (the client's
+ * device lookup covers that case through `work.linkPushedPullRequests`).
+ */
+export const githubPushShellWorkScanner: ShellWorkScanner = {
+ matches: (command) => command.includes('git') && command.includes('push'),
+ name: 'github-push',
+ register: async (input) => {
+ if (!input.pullRequestLinking) return null;
+
+ const push = parseGitPushResult({ command: input.data.command, output: input.transcript });
+ if (!push) return null;
+
+ const pullRequests = await input.pullRequestLinking.findOpenPullRequestsByHead(
+ push.repoFullName,
+ push.branches,
+ );
+ if (pullRequests.length === 0) return null;
+
+ const works = [];
+ for (const pullRequest of pullRequests) {
+ const identifier = `${pullRequest.repoFullName}#${pullRequest.number}`;
+ works.push(
+ await input.workModel.registerExternal({
+ agentId: input.agentId,
+ changeType: 'updated',
+ cumulativeCost: input.cumulativeCost,
+ cumulativeUsage: input.cumulativeUsage,
+ identifier,
+ messageId: input.messageId,
+ ...(pullRequest.headRef ? { metadata: { headBranch: pullRequest.headRef } } : {}),
+ patchFields: pullRequest.title ? ['identifier', 'title', 'url'] : ['identifier', 'url'],
+ resourceId: identifier,
+ resourceType: 'github_pull_request',
+ rootOperationId: input.rootOperationId,
+ threadId: input.threadId,
+ title: pullRequest.title,
+ toolCallId: input.toolCallId,
+ toolIdentifier: input.toolIdentifier,
+ toolName: input.toolName,
+ topicId: input.topicId,
+ url: pullRequest.url,
+ }),
+ );
+ }
+ return works;
+ },
+ requiresPullRequestLinking: true,
+};
diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/index.ts b/apps/server/src/services/workRegistration/shellWorkScanners/index.ts
index 579f9f13294..5c3644db310 100644
--- a/apps/server/src/services/workRegistration/shellWorkScanners/index.ts
+++ b/apps/server/src/services/workRegistration/shellWorkScanners/index.ts
@@ -1,4 +1,5 @@
import { githubShellWorkScanner } from './github';
+import { githubPushShellWorkScanner } from './githubPush';
import type { ShellWorkScanner } from './types';
export type { ShellWorkScanner } from './types';
@@ -9,4 +10,7 @@ export type { ShellWorkScanner } from './types';
* `@/database/models/work`, define its scanner in a sibling file here, and
* append it to this list.
*/
-export const SHELL_WORK_SCANNERS: ShellWorkScanner[] = [githubShellWorkScanner];
+export const SHELL_WORK_SCANNERS: ShellWorkScanner[] = [
+ githubShellWorkScanner,
+ githubPushShellWorkScanner,
+];
diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/types.ts b/apps/server/src/services/workRegistration/shellWorkScanners/types.ts
index a4eefd36dd9..2f77f798ea5 100644
--- a/apps/server/src/services/workRegistration/shellWorkScanners/types.ts
+++ b/apps/server/src/services/workRegistration/shellWorkScanners/types.ts
@@ -2,6 +2,8 @@ import type { WorkVersionCumulativeUsage } from '@lobechat/types';
import type { WorkModel } from '@/database/models/work';
+import type { ShellPullRequestLinking } from '../pullRequestLinking';
+
/**
* One CLI family the shell Work scan knows how to turn into Works. The engine
* (`registerShellWorks` in `../shellWorkRegistration`) owns everything
@@ -30,12 +32,25 @@ export interface ShellWorkScanner {
cumulativeUsage: WorkVersionCumulativeUsage | null;
data: { command: string; exitCode?: number; output?: string };
messageId: string;
+ /** Present when the lab is on; see {@link ShellPullRequestLinking}. */
+ pullRequestLinking?: ShellPullRequestLinking;
rootOperationId: string;
threadId: string | null;
toolCallId: string | null;
toolIdentifier: string;
toolName: string;
topicId: string;
+ /**
+ * Every text the run left (stdout, stderr, combined output, message body)
+ * joined. `data.output` is the stdout-first pick the gh normalizer wants;
+ * git writes its push report to stderr, so a push needs all of it.
+ */
+ transcript: string;
workModel: WorkModel;
}) => Promise<unknown | null>;
+ /**
+ * Runs only when the scan carries {@link ShellPullRequestLinking} (the
+ * Better Coding Experience lab is on); without it the scanner is skipped.
+ */
+ requiresPullRequestLinking?: boolean;
}
diff --git a/apps/server/src/services/workRegistration/topicPullRequests.test.ts b/apps/server/src/services/workRegistration/topicPullRequests.test.ts
new file mode 100644
index 00000000000..92fd0513eb3
--- /dev/null
+++ b/apps/server/src/services/workRegistration/topicPullRequests.test.ts
@@ -0,0 +1,210 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { linkPushedPullRequests, listTopicPullRequestsWithStatus } from './topicPullRequests';
+
+const { getUserPreference, listByIdentities, listOpenByHeadRefs } = vi.hoisted(() => ({
+ getUserPreference: vi.fn(),
+ listByIdentities: vi.fn(),
+ listOpenByHeadRefs: vi.fn(),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn(function () {
+ return { getUserPreference };
+ }),
+}));
+
+vi.mock('@/database/models/scm', () => ({
+ ScmChangeRequestModel: { listByIdentities, listOpenByHeadRefs },
+}));
+
+const db = {} as any;
+
+const workItem = (number: number, repoFullName = 'lobehub/lobehub') => ({
+ identifier: `${repoFullName}#${number}`,
+ linkedAt: new Date('2026-11-17T00:00:00Z'),
+ number,
+ repoFullName,
+ status: 'open',
+ title: `PR ${number}`,
+ url: `https://github.com/${repoFullName}/pull/${number}`,
+ workId: `wk-${number}`,
+});
+
+describe('listTopicPullRequestsWithStatus', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('attaches the GitHub App state where a row is visible, null elsewhere', async () => {
+ const workModel = {
+ listTopicPullRequests: vi.fn(async () => [workItem(1), workItem(2)]),
+ } as any;
+ const updatedAt = new Date('2026-11-17T01:00:00Z');
+ listByIdentities.mockResolvedValue([
+ {
+ ciStatus: 'failure',
+ isDraft: false,
+ mergedAt: null,
+ number: 1,
+ repoFullName: 'LobeHub/LobeHub',
+ reviewDecision: 'approved',
+ state: 'open',
+ title: 'From the App',
+ updatedAt,
+ },
+ ]);
+
+ const items = await listTopicPullRequestsWithStatus({
+ db,
+ topicId: 't1',
+ userId: 'u1',
+ workModel,
+ workspaceId: 'ws1',
+ });
+
+ expect(listByIdentities).toHaveBeenCalledWith(db, { userId: 'u1', workspaceId: 'ws1' }, [
+ { number: 1, repoFullName: 'lobehub/lobehub' },
+ { number: 2, repoFullName: 'lobehub/lobehub' },
+ ]);
+ expect(items[0].scm).toEqual({
+ ciStatus: 'failure',
+ isDraft: false,
+ mergedAt: null,
+ reviewDecision: 'approved',
+ state: 'open',
+ title: 'From the App',
+ updatedAt,
+ });
+ expect(items[1].scm).toBeNull();
+ });
+
+ it('skips the scm lookup for a topic without pull requests', async () => {
+ const workModel = { listTopicPullRequests: vi.fn(async () => []) } as any;
+
+ expect(
+ await listTopicPullRequestsWithStatus({ db, topicId: 't1', userId: 'u1', workModel }),
+ ).toEqual([]);
+ expect(listByIdentities).not.toHaveBeenCalled();
+ });
+});
+
+describe('linkPushedPullRequests', () => {
+ const pushRow = {
+ apiName: 'Bash',
+ arguments: JSON.stringify({ command: 'git push origin HEAD' }),
+ content: 'To github.com:lobehub/lobehub.git\n 031bf96..f6b1c2a local -> feat/x',
+ id: 'msg-push',
+ identifier: 'claude-code',
+ toolCallId: 'toolu_1',
+ };
+
+ const createModels = (row: Record<string, unknown> | null = pushRow) => ({
+ messageModel: {
+ findToolMessageIdByToolCallId: vi.fn(async () => (row ? row.id : null)),
+ listMessagePluginsByIds: vi.fn(async () => (row ? [row] : [])),
+ } as any,
+ workModel: { registerExternal: vi.fn(async () => ({ id: 'wk' })) } as any,
+ });
+
+ const devicePR = {
+ headRefName: 'feat/x',
+ isDraft: false,
+ number: 12,
+ state: 'OPEN',
+ title: 'Feat X',
+ url: 'https://github.com/lobehub/lobehub/pull/12',
+ };
+
+ const link = (models: ReturnType<typeof createModels>, devicePullRequests = [devicePR]) =>
+ linkPushedPullRequests({
+ db,
+ devicePullRequests,
+ toolCallId: 'toolu_1',
+ topicId: 't1',
+ userId: 'u1',
+ ...models,
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });
+ listOpenByHeadRefs.mockResolvedValue([]);
+ });
+
+ it('does nothing while the lab is off', async () => {
+ getUserPreference.mockResolvedValue({ lab: {} });
+ const models = createModels();
+
+ expect(await link(models)).toEqual({ status: 'skipped' });
+ expect(models.messageModel.findToolMessageIdByToolCallId).not.toHaveBeenCalled();
+ });
+
+ it('prefers the GitHub App rows for the pushed branch', async () => {
+ listOpenByHeadRefs.mockResolvedValue([
+ {
+ headRef: 'feat/x',
+ number: 30,
+ repoFullName: 'lobehub/lobehub',
+ title: 'Tracked',
+ url: 'https://github.com/lobehub/lobehub/pull/30',
+ },
+ ]);
+ const models = createModels();
+
+ expect(await link(models)).toEqual({ linked: ['lobehub/lobehub#30'], status: 'linked' });
+ expect(listOpenByHeadRefs).toHaveBeenCalledWith(
+ db,
+ { userId: 'u1', workspaceId: null },
+ 'lobehub/lobehub',
+ ['feat/x'],
+ );
+ });
+
+ it('accepts the device answer only for the pushed repository and branch', async () => {
+ const models = createModels();
+
+ const result = await link(models, [
+ devicePR,
+ { ...devicePR, number: 13, url: 'https://github.com/someone/else/pull/13' },
+ {
+ ...devicePR,
+ headRefName: 'main',
+ number: 14,
+ url: 'https://github.com/lobehub/lobehub/pull/14',
+ },
+ { ...devicePR, number: 15, url: 'https://github.com/lobehub/lobehub/pull/99' },
+ ]);
+
+ expect(result).toEqual({ linked: ['lobehub/lobehub#12'], status: 'linked' });
+ expect(models.workModel.registerExternal).toHaveBeenCalledTimes(1);
+ expect(models.workModel.registerExternal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ changeType: 'updated',
+ messageId: 'msg-push',
+ metadata: { headBranch: 'feat/x' },
+ patchFields: ['identifier', 'url', 'title', 'status'],
+ resourceId: 'lobehub/lobehub#12',
+ status: 'open',
+ toolCallId: 'toolu_1#push-link',
+ toolIdentifier: 'claude-code',
+ toolName: 'Bash',
+ topicId: 't1',
+ }),
+ );
+ });
+
+ it('asks the client to retry while the push is not persisted yet', async () => {
+ expect(await link(createModels(null))).toEqual({ status: 'pending' });
+ expect(await link(createModels({ ...pushRow, content: '' }))).toEqual({ status: 'pending' });
+ });
+
+ it('refuses a call that was not a push', async () => {
+ const models = createModels({
+ ...pushRow,
+ arguments: JSON.stringify({ command: 'gh pr view 12' }),
+ content: 'title: Feat X',
+ });
+
+ expect(await link(models)).toEqual({ status: 'skipped' });
+ expect(models.workModel.registerExternal).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/workRegistration/topicPullRequests.ts b/apps/server/src/services/workRegistration/topicPullRequests.ts
new file mode 100644
index 00000000000..3f74feda082
--- /dev/null
+++ b/apps/server/src/services/workRegistration/topicPullRequests.ts
@@ -0,0 +1,229 @@
+import type {
+ ScmChangeRequestSnapshot,
+ ScmCiStatus,
+ ScmReviewDecision,
+ TopicPullRequestItem,
+ TopicPullRequestScmState,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import type { MessageModel } from '@/database/models/message';
+import { ScmChangeRequestModel } from '@/database/models/scm';
+import { parseGitPushResult, type WorkModel } from '@/database/models/work';
+import type { LobeChatDatabase } from '@/database/type';
+
+import {
+ createShellPullRequestLinking,
+ isBetterCodingExperienceEnabled,
+} from './pullRequestLinking';
+import { readShellCommandRecord } from './shellWorkRegistration';
+
+const log = debug('lobe-server:topic-pull-requests');
+
+const identityKey = (repoFullName: string, number: number) =>
+ `${repoFullName.toLowerCase()}#${number}`;
+
+/** The fields of a tracked change request this listing reports. */
+type ScmChangeRequestState = Pick<
+ ScmChangeRequestSnapshot,
+ 'isDraft' | 'mergedAt' | 'number' | 'repoFullName' | 'state' | 'title'
+> & {
+ ciStatus?: ScmCiStatus | null;
+ reviewDecision?: ScmReviewDecision | null;
+ updatedAt: Date;
+};
+
+const toScmState = (row: ScmChangeRequestState): TopicPullRequestScmState => ({
+ ciStatus: row.ciStatus ?? null,
+ isDraft: row.isDraft ?? false,
+ mergedAt: row.mergedAt ?? null,
+ reviewDecision: row.reviewDecision ?? null,
+ state: row.state,
+ title: row.title ?? null,
+ updatedAt: row.updatedAt,
+});
+
+/**
+ * Pull requests linked to a topic (its `github_pull_request` Work rows), each
+ * with the GitHub App's state when an installation the scope can see tracks
+ * the repository. `scm: null` means "not confirmed here": the client then asks
+ * the execution device, and only confirmed data may enable merge / close.
+ */
+export const listTopicPullRequestsWithStatus = async (params: {
+ db: LobeChatDatabase;
+ topicId: string;
+ userId: string;
+ workModel: WorkModel;
+ workspaceId?: string | null;
+}): Promise<TopicPullRequestItem[]> => {
+ const items = await params.workModel.listTopicPullRequests(params.topicId);
+ if (items.length === 0) return [];
+
+ const rows = await ScmChangeRequestModel.listByIdentities(
+ params.db,
+ { userId: params.userId, workspaceId: params.workspaceId ?? null },
+ items.map(({ number, repoFullName }) => ({ number, repoFullName })),
+ );
+ const byIdentity = new Map(rows.map((row) => [identityKey(row.repoFullName, row.number), row]));
+
+ return items.map((item) => {
+ const row = byIdentity.get(identityKey(item.repoFullName, item.number));
+ return { ...item, scm: row ? toScmState(row) : null };
+ });
+};
+
+/** One pull request the execution device found for a pushed branch (`gh pr list --head`). */
+export interface DeviceReportedPullRequest {
+ headRefName: string;
+ isDraft?: boolean;
+ number: number;
+ state?: string;
+ title?: string;
+ url: string;
+}
+
+export type LinkPushedPullRequestsResult =
+ | { linked: string[]; status: 'linked' }
+ /** The push's tool message is not persisted (or not parseable) yet — retry shortly. */
+ | { status: 'pending' }
+ | { status: 'skipped' };
+
+const PULL_URL_RE = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)\/?$/i;
+
+/**
+ * Link the pull requests a `git push` updated, right after the push (Better
+ * Coding Experience). The server re-reads the push from the persisted tool
+ * message — the client only names which call it was — and takes the
+ * repository and branches from git's own report. Which pull request heads the
+ * branch comes from, in order:
+ *
+ * 1. the GitHub App's rows, when an installation tracks the repository;
+ * 2. otherwise the execution device's `gh pr list --head` answer, accepted
+ * only for that same repository and one of the pushed branches. The device
+ * belongs to the caller, so this asserts nothing they could not already
+ * register by running `gh pr edit <n>` in the conversation.
+ */
+export const linkPushedPullRequests = async (params: {
+ db: LobeChatDatabase;
+ devicePullRequests: DeviceReportedPullRequest[];
+ messageModel: MessageModel;
+ toolCallId: string;
+ topicId: string;
+ userId: string;
+ workModel: WorkModel;
+ workspaceId?: string | null;
+}): Promise<LinkPushedPullRequestsResult> => {
+ if (!(await isBetterCodingExperienceEnabled(params.db, params.userId))) {
+ return { status: 'skipped' };
+ }
+
+ const messageId = await params.messageModel.findToolMessageIdByToolCallId(params.toolCallId);
+ if (!messageId) return { status: 'pending' };
+ const [record] = await params.messageModel.listMessagePluginsByIds({
+ ids: [messageId],
+ topicId: params.topicId,
+ });
+ if (!record) return { status: 'skipped' };
+
+ const shell = readShellCommandRecord({
+ apiName: record.apiName ?? '',
+ arguments: record.arguments,
+ content: record.content,
+ error: record.error,
+ id: record.id,
+ identifier: record.identifier,
+ state: record.state,
+ toolCallId: record.toolCallId ?? '',
+ });
+ if (!shell) return { status: 'skipped' };
+
+ const push = parseGitPushResult({ command: shell.data.command, output: shell.transcript });
+ // The tool row may still be streaming in when the client fires right at
+ // tool end; an empty transcript is "not yet", not "no push".
+ if (!push) return shell.transcript ? { status: 'skipped' } : { status: 'pending' };
+
+ const linking = createShellPullRequestLinking({
+ db: params.db,
+ topicId: params.topicId,
+ userId: params.userId,
+ workModel: params.workModel,
+ workspaceId: params.workspaceId,
+ });
+ const tracked = await linking.findOpenPullRequestsByHead(push.repoFullName, push.branches);
+
+ const branches = new Set(push.branches);
+ const candidates =
+ tracked.length > 0
+ ? tracked.map((pr) => ({
+ headRef: pr.headRef,
+ isDraft: undefined as boolean | undefined,
+ number: pr.number,
+ repoFullName: pr.repoFullName,
+ state: undefined as string | undefined,
+ title: pr.title,
+ url: pr.url,
+ }))
+ : params.devicePullRequests.flatMap((pr) => {
+ const match = PULL_URL_RE.exec(pr.url);
+ if (!match || Number(match[3]) !== pr.number) return [];
+ const repoFullName = `${match[1]}/${match[2]}`;
+ if (repoFullName.toLowerCase() !== push.repoFullName.toLowerCase()) return [];
+ if (!branches.has(pr.headRefName)) return [];
+ return [
+ {
+ headRef: pr.headRefName,
+ isDraft: pr.isDraft,
+ number: pr.number,
+ repoFullName,
+ state: pr.state,
+ title: pr.title ?? null,
+ url: pr.url,
+ },
+ ];
+ });
+
+ const linked: string[] = [];
+ for (const pr of candidates) {
+ const identifier = `${pr.repoFullName}#${pr.number}`;
+ const status =
+ pr.state === undefined
+ ? undefined
+ : pr.state.toLowerCase() === 'open'
+ ? pr.isDraft
+ ? 'draft'
+ : 'open'
+ : pr.state.toLowerCase();
+ try {
+ await params.workModel.registerExternal({
+ changeType: 'updated',
+ identifier,
+ messageId: record.id,
+ ...(pr.headRef ? { metadata: { headBranch: pr.headRef } } : {}),
+ patchFields: [
+ 'identifier',
+ 'url',
+ ...(pr.title ? (['title'] as const) : []),
+ ...(status ? (['status'] as const) : []),
+ ],
+ resourceId: identifier,
+ resourceType: 'github_pull_request',
+ status: status ?? null,
+ title: pr.title,
+ // Its own dedupe key: the completion scan registers this same push again
+ // with the run's provenance (rootOperationId / agent), which is what makes
+ // it render as the run's Work card — sharing the call id would make that
+ // later version a no-op and the card would never show it.
+ toolCallId: `${record.toolCallId ?? params.toolCallId}#push-link`,
+ toolIdentifier: record.identifier ?? 'unknown',
+ toolName: record.apiName ?? 'unknown',
+ topicId: params.topicId,
+ url: pr.url,
+ });
+ linked.push(identifier);
+ } catch (error) {
+ log('Failed to link %s to topic %s: %O', identifier, params.topicId, error);
+ }
+ }
+
+ return { linked, status: 'linked' };
+};
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index c54808b8f13..663d3dac73b 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -170,6 +170,7 @@
"workingDirectory.topicDescription": "Override Agent default for this conversation only",
"workingDirectory.topicLevel": "Conversation override",
"workingDirectory.topicOverride": "Override for this conversation",
+ "workingDirectory.topicPullRequestsTooltip": "{{title}} (+{{count}} more linked to this topic — click to see all)",
"workingDirectory.uncommittedChanges_one": "Uncommitted changes: {{count}} file",
"workingDirectory.uncommittedChanges_other": "Uncommitted changes: {{count}} files",
"workingDirectory.undo": "Undo",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 6e5dc469cf4..51d0606105e 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -170,6 +170,7 @@
"workingDirectory.topicDescription": "仅覆盖当前对话的工作目录",
"workingDirectory.topicLevel": "对话覆盖",
"workingDirectory.topicOverride": "为当前对话覆盖设置",
+ "workingDirectory.topicPullRequestsTooltip": "{{title}}(此话题还关联了 {{count}} 个 PR,点击查看全部)",
"workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件",
"workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件",
"workingDirectory.undo": "撤销",
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.lookup.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.lookup.test.ts
new file mode 100644
index 00000000000..234f9173b60
--- /dev/null
+++ b/packages/database/src/models/scm/__tests__/changeRequest.lookup.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { scmChangeRequests, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { ScmChangeRequestModel } from '../changeRequest';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'scm-lookup-user';
+const otherUserId = 'scm-lookup-other-user';
+const scope = { userId, workspaceId: null };
+
+const row = (number: number, overrides: Record<string, unknown> = {}) =>
+ ScmChangeRequestModel.upsert(serverDB, {
+ headRef: `feat/${number}`,
+ headSha: String(number).repeat(40).slice(0, 40),
+ number,
+ provider: 'github',
+ repoFullName: 'LobeHub/LobeHub',
+ state: 'open',
+ url: `https://github.com/LobeHub/LobeHub/pull/${number}`,
+ userId,
+ ...overrides,
+ });
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmChangeRequests);
+ await serverDB.delete(users);
+});
+
+describe('ScmChangeRequestModel.listByIdentities', () => {
+ it('matches owner/repo#number case-insensitively within the scope', async () => {
+ await row(1);
+ await row(2);
+ await row(3, { userId: otherUserId });
+
+ const rows = await ScmChangeRequestModel.listByIdentities(serverDB, scope, [
+ { number: 1, repoFullName: 'lobehub/lobehub' },
+ { number: 3, repoFullName: 'lobehub/lobehub' },
+ { number: 9, repoFullName: 'lobehub/lobehub' },
+ ]);
+
+ expect(rows.map((r) => r.number)).toEqual([1]);
+ expect(await ScmChangeRequestModel.listByIdentities(serverDB, scope, [])).toEqual([]);
+ });
+});
+
+describe('ScmChangeRequestModel.listOpenByHeadRefs', () => {
+ it('finds the open pull requests whose head a push updated', async () => {
+ await row(1, { headRef: 'feat/x' });
+ await row(2, { headRef: 'feat/x', state: 'closed' });
+ await row(3, { headRef: 'feat/y' });
+ await row(4, { headRef: 'feat/x', repoFullName: 'lobehub/other' });
+ await row(5, { headRef: 'feat/x', userId: otherUserId });
+
+ const rows = await ScmChangeRequestModel.listOpenByHeadRefs(
+ serverDB,
+ scope,
+ 'lobehub/LOBEHUB',
+ ['feat/x'],
+ );
+
+ expect(rows.map((r) => r.number)).toEqual([1]);
+ expect(await ScmChangeRequestModel.listOpenByHeadRefs(serverDB, scope, 'a/b', [])).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.ts
index 73b53c085f0..36c7237d6ed 100644
--- a/packages/database/src/models/scm/changeRequest.ts
+++ b/packages/database/src/models/scm/changeRequest.ts
@@ -20,6 +20,28 @@ const ownedByScope = (scope: { userId: string; workspaceId?: string | null }) =>
? eq(scmChangeRequests.workspaceId, scope.workspaceId)
: and(eq(scmChangeRequests.userId, scope.userId), isNull(scmChangeRequests.workspaceId));
+/**
+ * What a scope may read: its own change requests, plus everything on the
+ * installations it connected (see {@link ScmChangeRequestModel.listByScope}).
+ */
+const visibleToScope = (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+) => {
+ const connected = db
+ .select({ id: scmInstallations.id })
+ .from(scmInstallations)
+ .where(
+ and(
+ isNull(scmInstallations.revokedAt),
+ scope.workspaceId
+ ? eq(scmInstallations.workspaceId, scope.workspaceId)
+ : and(eq(scmInstallations.userId, scope.userId), isNull(scmInstallations.workspaceId)),
+ ),
+ );
+ return or(ownedByScope(scope), inArray(scmChangeRequests.installationId, connected));
+};
+
/**
* Conclusions worth waking an agent over: something broke and there is
* something to fix. A cancelled or stale run is not one of them — usually a
@@ -229,27 +251,70 @@ export class ScmChangeRequestModel {
db: LobeChatDatabase,
scope: { userId: string; workspaceId?: string | null },
options: { limit?: number } = {},
+ ): Promise<ScmChangeRequestItem[]> =>
+ db
+ .select()
+ .from(scmChangeRequests)
+ .where(visibleToScope(db, scope))
+ .orderBy(desc(scmChangeRequests.updatedAt))
+ .limit(options.limit ?? 50);
+
+ /**
+ * The rows a scope can see for these `owner/repo#number` identities, matched
+ * case-insensitively (GitHub names are). Same visibility as
+ * {@link listByScope}; an identity no installation tracks has no row.
+ */
+ static listByIdentities = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+ identities: { number: number; repoFullName: string }[],
): Promise<ScmChangeRequestItem[]> => {
- const owned = ownedByScope(scope);
+ if (identities.length === 0) return [];
- const connected = db
- .select({ id: scmInstallations.id })
- .from(scmInstallations)
+ return db
+ .select()
+ .from(scmChangeRequests)
.where(
and(
- isNull(scmInstallations.revokedAt),
- scope.workspaceId
- ? eq(scmInstallations.workspaceId, scope.workspaceId)
- : and(eq(scmInstallations.userId, scope.userId), isNull(scmInstallations.workspaceId)),
+ eq(scmChangeRequests.provider, 'github'),
+ or(
+ ...identities.map(({ number, repoFullName }) =>
+ and(
+ eq(scmChangeRequests.number, number),
+ sql`lower(${scmChangeRequests.repoFullName}) = ${repoFullName.toLowerCase()}`,
+ ),
+ ),
+ ),
+ visibleToScope(db, scope),
),
);
+ };
+
+ /**
+ * Open pull requests of `repoFullName` whose head is one of `branches`, as
+ * a scope can see them: what a `git push` to those branches updated.
+ */
+ static listOpenByHeadRefs = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+ repoFullName: string,
+ branches: string[],
+ ): Promise<ScmChangeRequestItem[]> => {
+ if (branches.length === 0) return [];
return db
.select()
.from(scmChangeRequests)
- .where(or(owned, inArray(scmChangeRequests.installationId, connected)))
- .orderBy(desc(scmChangeRequests.updatedAt))
- .limit(options.limit ?? 50);
+ .where(
+ and(
+ eq(scmChangeRequests.provider, 'github'),
+ sql`lower(${scmChangeRequests.repoFullName}) = ${repoFullName.toLowerCase()}`,
+ inArray(scmChangeRequests.headRef, branches),
+ eq(scmChangeRequests.state, 'open'),
+ visibleToScope(db, scope),
+ ),
+ )
+ .orderBy(desc(scmChangeRequests.updatedAt));
};
/**
diff --git a/packages/database/src/models/work/__tests__/gitPushResult.test.ts b/packages/database/src/models/work/__tests__/gitPushResult.test.ts
new file mode 100644
index 00000000000..2bd3bdda09b
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/gitPushResult.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseGithubRemoteUrl, parseGitPushResult } from '../gitPushResult';
+
+describe('parseGithubRemoteUrl', () => {
+ it.each([
+ ['https://github.com/lobehub/lobehub.git', 'lobehub/lobehub'],
+ ['https://github.com/lobehub/lobehub', 'lobehub/lobehub'],
+ ['https://x-access-token:[email protected]/lobehub/lobe-chat.git', 'lobehub/lobe-chat'],
+ ['[email protected]:lobehub/lobehub.git', 'lobehub/lobehub'],
+ ['ssh://[email protected]/lobehub/lobehub.git', 'lobehub/lobehub'],
+ ])('reads %s', (url, repo) => {
+ expect(parseGithubRemoteUrl(url)).toBe(repo);
+ });
+
+ it('rejects non-GitHub remotes', () => {
+ expect(parseGithubRemoteUrl('https://gitlab.com/a/b.git')).toBeNull();
+ expect(parseGithubRemoteUrl('/tmp/repo.git')).toBeNull();
+ });
+});
+
+describe('parseGitPushResult', () => {
+ it('reads the repository and published branches of a push', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git push -u origin HEAD',
+ output: [
+ 'remote: Resolving deltas: 100% (2/2)',
+ 'To github.com:lobehub/lobehub.git',
+ ' * [new branch] worktree-feat+x -> feat/x',
+ "branch 'worktree-feat+x' set up to track 'origin/feat/x'.",
+ ].join('\n'),
+ }),
+ ).toEqual({ branches: ['feat/x'], repoFullName: 'lobehub/lobehub' });
+ });
+
+ it('accepts fast-forward and forced updates', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git add -A && git commit -m wip && git push --force-with-lease',
+ output: [
+ 'To https://github.com/lobehub/lobehub.git',
+ ' + 031bf96...f6b1c2a feat/y -> feat/y (forced update)',
+ ' 031bf96..f6b1c2a feat/z -> refs/heads/feat/z',
+ ].join('\n'),
+ })?.branches,
+ ).toEqual(['feat/y', 'feat/z']);
+ });
+
+ it('accepts git global options before push', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git -C /tmp/repo push',
+ output: 'To github.com:a/b.git\n 1234abc..5678def main -> main',
+ }),
+ ).toEqual({ branches: ['main'], repoFullName: 'a/b' });
+ });
+
+ it('ignores rejected, deleted and tag refs', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git push origin --all --tags',
+ output: [
+ 'To github.com:a/b.git',
+ ' ! [rejected] feat/x -> feat/x (non-fast-forward)',
+ ' - [deleted] old',
+ ' * [new tag] v1.0.0 -> v1.0.0',
+ ].join('\n'),
+ }),
+ ).toBeNull();
+ });
+
+ it('does not attribute a push to two remotes', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git push origin feat && git push fork feat',
+ output: [
+ 'To github.com:a/b.git',
+ ' * [new branch] feat -> feat',
+ 'To github.com:me/b.git',
+ ' * [new branch] feat -> feat',
+ ].join('\n'),
+ }),
+ ).toBeNull();
+ });
+
+ it('needs a git push command and a GitHub destination', () => {
+ const output = 'To github.com:a/b.git\n * [new branch] feat -> feat';
+ expect(parseGitPushResult({ command: 'git status', output })).toBeNull();
+ expect(parseGitPushResult({ command: 'echo git push', output })).toBeNull();
+ expect(parseGitPushResult({ command: 'git push', output: '' })).toBeNull();
+ expect(
+ parseGitPushResult({
+ command: 'git push',
+ output: 'To gitlab.com:a/b.git\n * [new branch] feat -> feat',
+ }),
+ ).toBeNull();
+ });
+
+ it('ignores git commands that carry only options, and tag refs pushed by SHA range', () => {
+ expect(
+ parseGitPushResult({
+ command: 'git --version',
+ output: 'To github.com:a/b.git\n * [new branch] feat -> feat',
+ }),
+ ).toBeNull();
+ expect(
+ parseGitPushResult({
+ command: 'git -c push.default=current push --follow-tags',
+ output: [
+ 'To github.com:a/b.git',
+ ' 1234abc..5678def refs/tags/v1 -> refs/tags/v1',
+ ' 1234abc..5678def feat -> feat',
+ ].join('\n'),
+ }),
+ ).toEqual({ branches: ['feat'], repoFullName: 'a/b' });
+ });
+
+ it('ignores a dry run, which reports the table without publishing', () => {
+ const output = 'To github.com:a/b.git\n * [new branch] feat -> feat';
+ expect(parseGitPushResult({ command: 'git push --dry-run origin feat', output })).toBeNull();
+ expect(parseGitPushResult({ command: 'git push -un origin feat', output })).toBeNull();
+ expect(
+ parseGitPushResult({ command: 'git push -n origin feat && git push origin feat', output }),
+ ).toEqual({ branches: ['feat'], repoFullName: 'a/b' });
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/githubPullRequestLifecycle.test.ts b/packages/database/src/models/work/__tests__/githubPullRequestLifecycle.test.ts
new file mode 100644
index 00000000000..52c30b7f9b6
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/githubPullRequestLifecycle.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeGithubShellToolResult, normalizeGithubToolResult } from '../githubToolResult';
+
+const shell = (
+ command: string,
+ output = '',
+ options: Parameters<typeof normalizeGithubShellToolResult>[1] = { pullRequestLifecycle: true },
+) =>
+ normalizeGithubShellToolResult(
+ { data: { command, exitCode: 0, output }, toolName: 'Bash' },
+ options,
+ );
+
+describe('normalizeGithubShellToolResult (pull request lifecycle)', () => {
+ it('ignores gh pr ready / merge unless the caller opts in', () => {
+ expect(
+ normalizeGithubShellToolResult({
+ data: { command: 'gh pr merge 12 -R lobehub/lobehub --squash', exitCode: 0, output: '' },
+ toolName: 'Bash',
+ }),
+ ).toBeNull();
+ expect(shell('gh pr ready 12 -R lobehub/lobehub', '', {})).toBeNull();
+ });
+
+ it('marks a merged pull request named by number and --repo once gh confirms the merge', () => {
+ const operation = shell(
+ 'gh pr merge 12 -R lobehub/lobehub --squash --delete-branch',
+ '✓ Squashed and merged pull request lobehub/lobehub#12 (Fix tray)',
+ );
+
+ expect(operation?.params).toMatchObject({
+ changeType: 'updated',
+ identifier: 'lobehub/lobehub#12',
+ resourceType: 'github_pull_request',
+ status: 'merged',
+ });
+ expect(operation?.params.patchFields).toEqual(['identifier', 'status']);
+ });
+
+ it('treats the merge commit -t / -b as the commit, not the pull request', () => {
+ const operation = shell(
+ `gh pr merge 12 --repo lobehub/lobehub -s -t 'squash subject' -b 'squash body'`,
+ );
+
+ expect(operation?.params).toMatchObject({ identifier: 'lobehub/lobehub#12' });
+ expect(operation?.params.title).toBeUndefined();
+ expect(operation?.params.content).toBeUndefined();
+ });
+
+ it('does not let a -m / -r merge switch swallow the number', () => {
+ expect(shell('gh pr merge -m 7 -R lobehub/lobehub')?.params.identifier).toBe(
+ 'lobehub/lobehub#7',
+ );
+ expect(shell('gh pr merge -r 8 -R lobehub/lobehub')?.params.identifier).toBe(
+ 'lobehub/lobehub#8',
+ );
+ });
+
+ it('links an auto-merge request without claiming the pull request merged', () => {
+ const operation = shell('gh pr merge 12 -R lobehub/lobehub --auto --squash');
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#12');
+ expect(operation?.params.status).toBeUndefined();
+ expect(operation?.params.patchFields).toEqual(['identifier']);
+ });
+
+ it('records ready as open and ready --undo as draft', () => {
+ expect(shell('gh pr ready 3 -R lobehub/lobehub')?.params.status).toBe('open');
+ expect(shell('gh pr ready 3 -R lobehub/lobehub --undo')?.params.status).toBe('draft');
+ });
+
+ it('takes the repository from a pull request URL target', () => {
+ const operation = shell('gh pr merge https://github.com/lobehub/lobehub/pull/44 --merge');
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#44',
+ url: 'https://github.com/lobehub/lobehub/pull/44',
+ });
+ });
+
+ it('reads the repository from the terminal confirmation line', () => {
+ const operation = shell(
+ 'gh pr merge 9 --squash',
+ '✓ Squashed and merged pull request lobehub/lobehub#9 (Fix tray)\n',
+ );
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#9');
+ });
+
+ it('falls back to the one pull request of that number already linked to the topic', () => {
+ expect(
+ shell('gh pr ready 9', '', {
+ pullRequestLifecycle: true,
+ topicPullRequests: ['lobehub/lobehub#9', 'lobehub/other#3'],
+ })?.params.identifier,
+ ).toBe('lobehub/lobehub#9');
+ });
+
+ it('registers nothing when the number cannot be placed in a repository', () => {
+ expect(shell('gh pr ready 9', '', { pullRequestLifecycle: true })).toBeNull();
+ expect(
+ shell('gh pr ready 9', '', {
+ pullRequestLifecycle: true,
+ topicPullRequests: ['a/one#9', 'b/two#9'],
+ }),
+ ).toBeNull();
+ });
+
+ it('ignores a lifecycle command without a pull request number', () => {
+ expect(shell('gh pr merge --squash')).toBeNull();
+ expect(
+ shell('gh pr ready', '', { pullRequestLifecycle: true, topicPullRequests: [] }),
+ ).toBeNull();
+ });
+
+ it('trusts the target over URLs a chained segment printed', () => {
+ const operation = shell(
+ 'gh pr merge 5 -R lobehub/lobehub && gh pr list',
+ 'https://github.com/lobehub/lobehub/pull/99\n',
+ );
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#5');
+ });
+
+ it('never links a pull request that was only viewed, diffed, checked out or reviewed', () => {
+ for (const command of [
+ 'gh pr view 5 -R lobehub/lobehub',
+ 'gh pr diff 5 -R lobehub/lobehub',
+ 'gh pr checkout 5 -R lobehub/lobehub',
+ 'gh pr review 5 -R lobehub/lobehub --approve',
+ ]) {
+ expect(shell(command, 'https://github.com/lobehub/lobehub/pull/5')).toBeNull();
+ }
+ });
+
+ it('keeps an edit from overwriting the status', () => {
+ const operation = shell(
+ `gh pr edit 5 -R lobehub/lobehub --title 'New title'`,
+ 'https://github.com/lobehub/lobehub/pull/5',
+ );
+
+ expect(operation?.params.status).toBeUndefined();
+ expect(operation?.params.patchFields).not.toContain('status');
+ });
+
+ it('leaves the github skill runCommand surface without lifecycle commands', () => {
+ expect(
+ normalizeGithubToolResult({
+ data: { command: 'gh pr merge 12 -R lobehub/lobehub', exitCode: 0, output: '' },
+ toolName: 'runCommand',
+ }),
+ ).toBeNull();
+ });
+
+ it('links but does not claim merged when gh only queued the merge or printed nothing', () => {
+ for (const output of [
+ '',
+ '✓ Pull request lobehub/lobehub#12 will be added to the merge queue for main when ready',
+ ]) {
+ const operation = shell('gh pr merge 12 -R lobehub/lobehub --squash', output);
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#12');
+ expect(operation?.params.status).toBeUndefined();
+ }
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/pullRequests.test.ts b/packages/database/src/models/work/__tests__/pullRequests.test.ts
new file mode 100644
index 00000000000..887ce400546
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/pullRequests.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import type { RegisterExternalWorkParams } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { topics } from '../../../schemas';
+import { WorkModel } from '..';
+import {
+ cleanupWorkTestData,
+ seedWorkTestData,
+ serverDB,
+ threadId,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+const pr = (
+ identifier: string,
+ toolCallId: string,
+ overrides: Partial<RegisterExternalWorkParams> = {},
+): RegisterExternalWorkParams => ({
+ changeType: 'created',
+ identifier,
+ patchFields: ['identifier', 'title', 'status', 'url'],
+ resourceId: identifier,
+ resourceType: 'github_pull_request',
+ status: 'open',
+ title: `PR ${identifier}`,
+ toolCallId,
+ toolIdentifier: 'claude-code',
+ toolName: 'Bash',
+ topicId,
+ url: `https://github.com/${identifier.replace('#', '/pull/')}`,
+ ...overrides,
+});
+
+describe('WorkModel.listTopicPullRequests', () => {
+ it('lists every pull request linked to the topic once, latest link first', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerExternal(
+ pr('lobehub/lobehub#1', 'call-1', {
+ metadata: { baseBranch: 'canary', headBranch: 'feat/a' },
+ }),
+ );
+ await model.registerExternal(pr('lobehub/lobehub#2', 'call-2', { threadId }));
+ // A later command on #1 (merge) links it again — still one row, now newest.
+ await model.registerExternal(
+ pr('lobehub/lobehub#1', 'call-3', {
+ changeType: 'updated',
+ patchFields: ['identifier', 'status'],
+ status: 'merged',
+ }),
+ );
+
+ const items = await model.listTopicPullRequests(topicId);
+
+ expect(items.map((item) => item.identifier)).toEqual([
+ 'lobehub/lobehub#1',
+ 'lobehub/lobehub#2',
+ ]);
+ expect(items[0]).toMatchObject({
+ baseBranch: 'canary',
+ headBranch: 'feat/a',
+ number: 1,
+ repoFullName: 'lobehub/lobehub',
+ status: 'merged',
+ title: 'PR lobehub/lobehub#1',
+ url: 'https://github.com/lobehub/lobehub/pull/1',
+ });
+ expect(items[0].linkedAt).toBeInstanceOf(Date);
+ });
+
+ it('ignores issues, other topics and other users', async () => {
+ const otherTopicId = 'work-test-other-topic';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+ const model = new WorkModel(serverDB, userId);
+ await model.registerExternal(
+ pr('lobehub/lobehub#3', 'call-issue', { resourceType: 'github_issue' }),
+ );
+ await model.registerExternal(pr('lobehub/lobehub#4', 'call-other', { topicId: otherTopicId }));
+ await new WorkModel(serverDB, userId2).registerExternal(pr('lobehub/lobehub#5', 'call-user2'));
+
+ expect(await model.listTopicPullRequests(topicId)).toEqual([]);
+ expect((await model.listTopicPullRequests(otherTopicId)).map((i) => i.number)).toEqual([4]);
+ });
+
+ it('includes a pull request first registered in another topic once this topic touches it', async () => {
+ const otherTopicId = 'work-test-origin-topic';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+ const model = new WorkModel(serverDB, userId);
+ await model.registerExternal(pr('lobehub/lobehub#6', 'call-origin', { topicId: otherTopicId }));
+ await model.registerExternal(
+ pr('lobehub/lobehub#6', 'call-here', { changeType: 'updated', patchFields: ['identifier'] }),
+ );
+
+ expect((await model.listTopicPullRequests(topicId)).map((i) => i.number)).toEqual([6]);
+ });
+
+ it('skips a pull request Work whose identity is not owner/repo#number', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerExternal(pr('lobehub/lobehub#7', 'call-ok'));
+ await model.registerExternal({
+ ...pr('lobehub/lobehub#7', 'call-bad'),
+ identifier: 'not-a-pr',
+ resourceId: 'not-a-pr',
+ });
+
+ expect((await model.listTopicPullRequests(topicId)).map((i) => i.identifier)).toEqual([
+ 'lobehub/lobehub#7',
+ ]);
+ });
+});
diff --git a/packages/database/src/models/work/gitPushResult.ts b/packages/database/src/models/work/gitPushResult.ts
new file mode 100644
index 00000000000..2e1dd5fbd05
--- /dev/null
+++ b/packages/database/src/models/work/gitPushResult.ts
@@ -0,0 +1,109 @@
+import { parseShellCommandSegments } from './shellCommandParsing';
+
+/** What a successful `git push` published, as its own output reported it. */
+export interface GitPushResult {
+ /** Branch names ON the remote that now hold the pushed commits. */
+ branches: string[];
+ /** `owner/repo` of the GitHub remote the push went to. */
+ repoFullName: string;
+}
+
+/** `git` global options that consume the following token (`git -C dir push`). */
+const GIT_GLOBAL_VALUE_FLAGS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
+
+/** `-n` / `--dry-run`, also inside a short-flag cluster (`-un`): git prints the table but publishes nothing. */
+const isDryRunFlag = (token: string) =>
+ token === '--dry-run' || /^-[a-zA-Z]*n[a-zA-Z]*$/.test(token);
+
+/** A `git push` that publishes — a dry run reports the same table without pushing. */
+const isGitPushSegment = (segment: string[]): boolean => {
+ if (segment[0] !== 'git' && !segment[0]?.endsWith('/git')) return false;
+
+ for (let i = 1; i < segment.length; i++) {
+ const token = segment[i];
+ if (GIT_GLOBAL_VALUE_FLAGS.has(token)) {
+ i++;
+ continue;
+ }
+ if (token.startsWith('-')) continue;
+ return token === 'push' && !segment.slice(i + 1).some(isDryRunFlag);
+ }
+ return false;
+};
+
+/**
+ * The `To <url>` header git prints above each remote's ref table. Only a
+ * github.com remote names a repository we can link pull requests in.
+ */
+const PUSH_DESTINATION_LINE = /^To\s+(\S+)\s*$/;
+
+/**
+ * git anonymizes the URL it prints (`[email protected]:a/b.git` → `github.com:a/b.git`),
+ * so the scp-like form is accepted with or without a user.
+ */
+const GITHUB_REMOTE_RE =
+ /^(?:https?:\/\/(?:[^@/\s]+@)?github\.com\/|ssh:\/\/(?:[^@/\s]+@)?github\.com(?::\d+)?\/|(?:[^@/\s]+@)?github\.com:)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i;
+
+export const parseGithubRemoteUrl = (url: string): string | null => {
+ const match = GITHUB_REMOTE_RE.exec(url.trim());
+ return match ? `${match[1]}/${match[2]}` : null;
+};
+
+/**
+ * A ref line of git's push status table (`git push --porcelain` aside):
+ *
+ * ```
+ * * [new branch] feat/x -> feat/x
+ * 031bf96..f6b1c2a local -> feat/y
+ * + 031bf96...f6b1c2a local -> feat/y (forced update)
+ * ```
+ *
+ * Mirrors the client recorder (`worktreeDetection.parsePushRefMappings`): a
+ * rejected, deleted or tag ref never counts as a published branch.
+ */
+const PUSH_REF_LINE =
+ /^\s*(?:\S\s+)?(\[[^\]]*\]|[\da-f]{4,40}\.{2,3}[\da-f]{4,40})\s+(\S+)\s+->\s+(\S+)(?:\s+\(.*\))?\s*$/i;
+const PUSH_SUCCESS_STATUS = /^\[(?:new branch|new reference|up to date)\]$/i;
+
+/**
+ * Parse a shell run that pushed to GitHub. Returns null unless the command
+ * contains a `git push` AND its output names exactly one GitHub destination
+ * with at least one published branch — a push to two remotes, or output with
+ * no ref table (a quiet push, a failure), is not something we can attribute.
+ */
+export const parseGitPushResult = (params: {
+ command: string;
+ output?: string | null;
+}): GitPushResult | null => {
+ const segments = parseShellCommandSegments(params.command);
+ if (!segments?.some(isGitPushSegment)) return null;
+ if (!params.output) return null;
+
+ const destinations = new Map<string, Set<string>>();
+ let current: Set<string> | null = null;
+
+ for (const line of params.output.split('\n')) {
+ const destination = PUSH_DESTINATION_LINE.exec(line.trim());
+ if (destination) {
+ const repo = parseGithubRemoteUrl(destination[1]);
+ current = repo ? (destinations.get(repo) ?? new Set<string>()) : null;
+ if (repo && current) destinations.set(repo, current);
+ continue;
+ }
+ if (!current) continue;
+
+ const ref = PUSH_REF_LINE.exec(line);
+ if (!ref) continue;
+ const [, status, local, remote] = ref;
+ if (status.startsWith('[') && !PUSH_SUCCESS_STATUS.test(status)) continue;
+ if (local === '(none)' || local.startsWith('refs/tags/') || remote.startsWith('refs/tags/'))
+ continue;
+ current.add(remote.replace(/^refs\/heads\//, ''));
+ }
+
+ const published = [...destinations].filter(([, branches]) => branches.size > 0);
+ if (published.length !== 1) return null;
+
+ const [[repoFullName, branches]] = published;
+ return { branches: [...branches], repoFullName };
+};
diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.ts
index 83955a68f63..2232be4dd83 100644
--- a/packages/database/src/models/work/githubToolResult.ts
+++ b/packages/database/src/models/work/githubToolResult.ts
@@ -284,6 +284,10 @@ const buildParams = (
*/
const GH_VALUE_FLAGS = new Set([
'--add-assignee',
+ '--author-email',
+ '--match-head-commit',
+ '--subject',
+ '-A',
'--add-label',
'--add-project',
'--add-reviewer',
@@ -318,6 +322,13 @@ const GH_VALUE_FLAGS = new Set([
'-t',
]);
+/**
+ * `gh pr merge` switches that share a short name with a value flag of
+ * create/edit (`-m` milestone, `-r` reviewer): on merge they pick the method and
+ * take no value, so the pull request number after them must not be swallowed.
+ */
+const GH_MERGE_SWITCHES = new Set(['-m', '-r']);
+
interface GithubEntityRef {
entityType: GithubWorkEntityType;
number: number;
@@ -327,6 +338,26 @@ interface GithubEntityRef {
const GITHUB_ENTITY_URL_RE = /https?:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(issues|pull)\/(\d+)/gi;
+/**
+ * `owner/repo#123` mentions. `gh pr merge` / `gh pr ready` print no URL, only a
+ * `✓ Merged pull request owner/repo#123 (title)` line — and only to a terminal,
+ * so this is a best effort on top of the command's own target.
+ */
+const GITHUB_ENTITY_REF_RE = /(?:^|[\s(])([\w.-]+)\/([\w.-]+)#(\d+)\b/g;
+
+const parseGithubEntityRefs = (
+ text: string | null,
+ entityType: GithubWorkEntityType,
+): Omit<GithubEntityRef, 'url'>[] => {
+ if (!text) return [];
+
+ return Array.from(text.matchAll(GITHUB_ENTITY_REF_RE), (match) => ({
+ entityType,
+ number: Number(match[3]),
+ repo: `${match[1]}/${match[2]}`,
+ }));
+};
+
const parseGithubEntityUrls = (text: string | null): GithubEntityRef[] => {
if (!text) return [];
@@ -338,8 +369,18 @@ const parseGithubEntityUrls = (text: string | null): GithubEntityRef[] => {
}));
};
+/**
+ * Pull request lifecycle commands, recognized only when the caller opts in
+ * ({@link GithubShellNormalizeOptions.pullRequestLifecycle}). `gh pr view` /
+ * `diff` / `checkout` / `review` stay out on purpose: reading or reviewing
+ * someone else's pull request must not tie it to the conversation.
+ */
+type GhLifecycleAction = 'merge' | 'ready';
+
interface ParsedGhCommand {
- action: 'create' | 'edit';
+ action: 'create' | 'edit' | GhLifecycleAction;
+ /** `gh pr merge --auto` only queues the merge; `--disable-auto` cancels it. */
+ autoMerge: boolean;
/** `--base`: set on `gh pr create`, or changed by `gh pr edit`. */
base: string | null;
body: string | null;
@@ -351,16 +392,24 @@ interface ParsedGhCommand {
targetNumber: number | null;
targetRef: GithubEntityRef | null;
title: string | null;
+ /** `gh pr ready --undo` turns the pull request back into a draft. */
+ undo: boolean;
}
-const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
+const isLifecycleAction = (action: string): action is GhLifecycleAction =>
+ action === 'merge' || action === 'ready';
+
+const parseGhSegment = (segment: string[], lifecycle: boolean): ParsedGhCommand | null => {
if (segment[0] !== 'gh') return null;
const noun = segment[1];
const action = segment[2];
if (noun !== 'issue' && noun !== 'pr') return null;
- if (action !== 'create' && action !== 'edit') return null;
+ const isLifecycle = lifecycle && noun === 'pr' && isLifecycleAction(action);
+ if (action !== 'create' && action !== 'edit' && !isLifecycle) return null;
+ let autoMerge = false;
+ let undo = false;
let base: string | null = null;
let body: string | null = null;
let draft = false;
@@ -384,20 +433,31 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
continue;
}
- if (value === null && GH_VALUE_FLAGS.has(token)) {
+ const takesValue = GH_VALUE_FLAGS.has(token) && !(isLifecycle && GH_MERGE_SWITCHES.has(token));
+ if (value === null && takesValue) {
value = segment[i + 1] ?? null;
i++;
}
switch (token) {
+ // On `gh pr merge`, -t / -b name the merge COMMIT, not the pull request.
case '-t':
case '--title': {
- title = value;
+ if (!isLifecycle) title = value;
break;
}
case '-b':
case '--body': {
- body = value;
+ if (!isLifecycle) body = value;
+ break;
+ }
+ case '--auto':
+ case '--disable-auto': {
+ autoMerge = true;
+ break;
+ }
+ case '--undo': {
+ undo = true;
break;
}
case '-R':
@@ -443,7 +503,8 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
const isPullRequest = noun === 'pr';
return {
- action,
+ action: action as ParsedGhCommand['action'],
+ autoMerge,
base: isPullRequest ? base : null,
body,
draft,
@@ -453,11 +514,53 @@ const parseGhSegment = (segment: string[]): ParsedGhCommand | null => {
targetNumber,
targetRef,
title,
+ undo,
};
};
+/** Options for the shell-surface gh normalizer; both are off for the github skill. */
+export interface GithubShellNormalizeOptions {
+ /**
+ * Also register `gh pr ready <n>` / `gh pr merge <n>` (Better Coding
+ * Experience): touching a pull request by number ties it to the conversation.
+ */
+ pullRequestLifecycle?: boolean;
+ /**
+ * Pull requests (`owner/repo#n`) already linked to the conversation. A
+ * lifecycle command that names only a number — gh resolves the repository
+ * from the working directory, which the command text does not carry — is
+ * matched against these; an ambiguous or unknown number registers nothing.
+ */
+ topicPullRequests?: string[];
+}
+
+/**
+ * gh's confirmation that the merge itself happened (`✓ Merged pull request …`,
+ * `Squashed and merged`, `Rebased and merged`, `… was already merged`). A
+ * repository with a merge queue only queues the PR, and gh prints nothing at
+ * all to a non-terminal — neither is proof it merged.
+ */
+const MERGE_CONFIRMED_RE = /\b(?:merged pull request|was already merged)\b/i;
+
+/** What a lifecycle command leaves the pull request in; null when it does not say. */
+const lifecycleStatus = (parsed: ParsedGhCommand, output: string | null): string | null => {
+ if (parsed.action === 'merge') {
+ return !parsed.autoMerge && output && MERGE_CONFIRMED_RE.test(output) ? 'merged' : null;
+ }
+ if (parsed.action === 'ready') return parsed.undo ? 'draft' : 'open';
+ return null;
+};
+
+const resolveRepoFromTopic = (number: number, topicPullRequests: string[] = []) => {
+ const repos = topicPullRequests
+ .filter((identifier) => identifier.endsWith(`#${number}`))
+ .map((identifier) => identifier.slice(0, identifier.lastIndexOf('#')));
+ return repos.length === 1 ? repos[0] : null;
+};
+
const normalizeGithubCliResult = (
params: SkillToolResultWorkInput,
+ options: GithubShellNormalizeOptions = {},
): ExternalToolWorkOperation | null => {
const record = unwrapData(params.data);
if (!record) return null;
@@ -475,27 +578,49 @@ const normalizeGithubCliResult = (
// A chained command (`git push && gh pr create ...`) reports one combined
// stdout; the trailing URL belongs to the last gh create/edit segment.
const parsed = segments
- .map(parseGhSegment)
+ .map((segment) => parseGhSegment(segment, !!options.pullRequestLifecycle))
.findLast((segment): segment is ParsedGhCommand => !!segment);
if (!parsed) return null;
+ const isLifecycle = isLifecycleAction(parsed.action);
+ // Only a NUMBERED lifecycle command counts: without one gh acts on whatever
+ // branch is checked out, which says nothing about which pull request it was.
+ if (isLifecycle && parsed.targetNumber === null && !parsed.targetRef) return null;
+
// stdout is the source of truth for identity: `gh issue/pr create|edit`
// prints the entity URL as its result line. Fall back to the edit target
// in the command when stdout carries no URL.
const output = fromRecord(record, ['output', 'stdout']);
- const ref =
- parseGithubEntityUrls(output).at(-1) ??
+ const targetRepo =
+ parsed.repo ??
+ (isLifecycle && parsed.targetNumber !== null
+ ? (parseGithubEntityRefs(output, parsed.entityType).find(
+ (ref) => ref.number === parsed.targetNumber,
+ )?.repo ?? resolveRepoFromTopic(parsed.targetNumber, options.topicPullRequests))
+ : null);
+ const commandRef =
parsed.targetRef ??
- (parsed.targetNumber !== null && parsed.repo
+ (parsed.targetNumber !== null && targetRepo
? {
entityType: parsed.entityType,
number: parsed.targetNumber,
- repo: parsed.repo,
+ repo: targetRepo,
url: null,
}
: null);
+ // A lifecycle command prints no URL of its own, so any URL in a chained
+ // command's output belongs to another segment: trust only the target.
+ const ref = isLifecycle ? commandRef : (parseGithubEntityUrls(output).at(-1) ?? commandRef);
if (!ref) return null;
+ const status = isLifecycle
+ ? lifecycleStatus(parsed, output)
+ : parsed.action === 'create'
+ ? parsed.draft
+ ? 'draft'
+ : 'open'
+ : null;
+
const identifier = `${ref.repo}#${ref.number}`;
// Allowlist http(s) only: the url is parsed from member-controlled `gh`
@@ -520,8 +645,9 @@ const normalizeGithubCliResult = (
messageId: params.messageId ?? null,
metadata: branchMetadata(parsed.head, parsed.base),
rootOperationId: params.rootOperationId ?? null,
- // gh only exposes --draft on create; an edit carries no status signal.
- status: patch('status', parsed.action === 'create', parsed.draft ? 'draft' : 'open'),
+ // gh only exposes --draft on create; an edit carries no status signal,
+ // while merge / ready say what they left the pull request in.
+ status: patch('status', status !== null, status),
threadId: params.threadId ?? null,
title: patch('title', parsed.title !== null, stringValue(parsed.title)),
toolCallId: params.toolCallId ?? null,
@@ -549,10 +675,11 @@ const normalizeGithubCliResult = (
*/
export const normalizeGithubShellToolResult = (
params: SkillToolResultWorkInput,
+ options?: GithubShellNormalizeOptions,
): ExternalToolWorkOperation | null => {
if (isApplicationError(params.data)) return null;
- return normalizeGithubCliResult(params);
+ return normalizeGithubCliResult(params, options);
};
export const normalizeGithubToolResult = (
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index b2e30dcb06d..228e36d8664 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -33,13 +33,18 @@ import type { WorkContext } from './context';
import { registerDocumentWork } from './document';
import { registerExternalWork } from './external';
import { findFileWorkVersionByToolCall, registerFileWork } from './file';
-import { normalizeGithubShellToolResult, normalizeGithubToolResult } from './githubToolResult';
+import {
+ type GithubShellNormalizeOptions,
+ normalizeGithubShellToolResult,
+ normalizeGithubToolResult,
+} from './githubToolResult';
import {
findLatestGoalReportVersion,
registerGoalReportWork,
type RegisterGoalReportWorkParams,
} from './goalReport';
import { normalizeLinearToolResult } from './linearToolResult';
+import { listTopicPullRequests } from './pullRequests';
import * as queries from './queries';
import { registerTaskWork } from './task';
import type { ExternalToolWorkOperation } from './toolResultParsing';
@@ -65,6 +70,9 @@ const SKILL_TOOL_RESULT_NORMALIZERS = {
* module, keeping the polymorphic Work registry logic split by provider type
* without changing the public API surface.
*/
+export type { GithubShellNormalizeOptions } from './githubToolResult';
+export { type GitPushResult, parseGithubRemoteUrl, parseGitPushResult } from './gitPushResult';
+
export class WorkModel {
private readonly ctx: WorkContext;
@@ -164,10 +172,11 @@ export class WorkModel {
*/
registerShellGithubResult = async (
params: SkillToolResultWorkInput & { toolIdentifier: string },
+ options?: GithubShellNormalizeOptions,
): Promise<WorkItem | null> => {
const { toolIdentifier, ...rest } = params;
- const operation = normalizeGithubShellToolResult(rest);
+ const operation = normalizeGithubShellToolResult(rest, options);
if (!operation) return null;
return this.registerExternal({ ...operation.params, toolIdentifier });
@@ -221,4 +230,7 @@ export class WorkModel {
queries.listByWorkspace(this.ctx, params);
listVersions = (workId: string) => queries.listVersions(this.ctx, workId);
+
+ /** See {@link listTopicPullRequests}. */
+ listTopicPullRequests = (topicId: string) => listTopicPullRequests(this.ctx, topicId);
}
diff --git a/packages/database/src/models/work/pullRequests.ts b/packages/database/src/models/work/pullRequests.ts
new file mode 100644
index 00000000000..82092c4a9cc
--- /dev/null
+++ b/packages/database/src/models/work/pullRequests.ts
@@ -0,0 +1,85 @@
+import type { TopicPullRequestWork, WorkVersionMetadata } from '@lobechat/types';
+import { and, desc, eq, inArray, isNotNull, sql } from 'drizzle-orm';
+
+import { works, workVersions } from '../../schemas/work';
+import { type WorkContext, workOwnership } from './context';
+
+/** A topic links a handful of pull requests; this only bounds a runaway topic. */
+const TOPIC_PULL_REQUEST_LIMIT = 50;
+
+const parseIdentifier = (resourceId: string) => {
+ const hash = resourceId.lastIndexOf('#');
+ const number = Number(resourceId.slice(hash + 1));
+ if (hash <= 0 || !Number.isInteger(number) || number <= 0) return null;
+ return { number, repoFullName: resourceId.slice(0, hash) };
+};
+
+/**
+ * GitHub pull requests linked to a topic, most recently linked first. A pull
+ * request is linked by ANY version of its Work registered in the topic (any
+ * thread), so it shows once however many commands touched it, and a Work
+ * first registered elsewhere still appears once the topic touches it.
+ */
+export const listTopicPullRequests = async (
+ ctx: WorkContext,
+ topicId: string,
+): Promise<TopicPullRequestWork[]> => {
+ const linkedAt = sql<Date>`max(${workVersions.createdAt})`;
+ const rows = await ctx.db
+ .select({
+ currentVersionId: works.currentVersionId,
+ linkedAt,
+ resourceId: works.resourceId,
+ status: works.status,
+ title: works.title,
+ url: works.url,
+ workId: works.id,
+ })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(
+ and(
+ eq(workVersions.topicId, topicId),
+ eq(works.type, 'external'),
+ eq(works.resourceType, 'github_pull_request'),
+ isNotNull(works.resourceId),
+ ),
+ )
+ .groupBy(works.id)
+ .orderBy(desc(linkedAt), desc(works.id))
+ .limit(TOPIC_PULL_REQUEST_LIMIT);
+
+ const versionIds = rows.map((row) => row.currentVersionId).filter((id): id is string => !!id);
+ // The current version carries the merged branch metadata (an edit that names
+ // no branch keeps the one captured at create).
+ const branches = new Map<string, WorkVersionMetadata | null>();
+ if (versionIds.length > 0) {
+ const versions = await ctx.db
+ .select({ id: workVersions.id, metadata: workVersions.metadata })
+ .from(workVersions)
+ .where(inArray(workVersions.id, versionIds));
+ for (const version of versions) branches.set(version.id, version.metadata);
+ }
+
+ return rows.flatMap((row) => {
+ const identity = row.resourceId ? parseIdentifier(row.resourceId) : null;
+ if (!identity) return [];
+ const metadata = row.currentVersionId ? branches.get(row.currentVersionId) : undefined;
+
+ return [
+ {
+ ...(metadata?.baseBranch ? { baseBranch: metadata.baseBranch } : {}),
+ ...(metadata?.headBranch ? { headBranch: metadata.headBranch } : {}),
+ identifier: row.resourceId!,
+ // `max()` comes back as text through some drivers.
+ linkedAt: new Date(row.linkedAt),
+ number: identity.number,
+ repoFullName: identity.repoFullName,
+ status: row.status,
+ title: row.title,
+ url: row.url,
+ workId: row.workId,
+ },
+ ];
+ });
+};
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 615fce62a9b..21e597e1a98 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -89,6 +89,8 @@ export default {
'workingDirectory.pathNotExist': "This path doesn't exist on the device",
'workingDirectory.placeholder': 'Enter directory path, e.g. /Users/name/projects',
'workingDirectory.prTooltipWithExtra': '{{title}} (+{{count}} more open PR on this branch)',
+ 'workingDirectory.topicPullRequestsTooltip':
+ '{{title}} (+{{count}} more linked to this topic — click to see all)',
'workingDirectory.pullAction': 'Click to pull {{count}} commit(s) from {{upstream}}',
'workingDirectory.pullFailed': 'Pull failed',
'workingDirectory.pullInProgress': 'Pulling…',
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index 924705c05b9..da62b1beb95 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -655,3 +655,44 @@ export type WorkRegistrationIntent =
};
type: 'canvas';
};
+
+/**
+ * One GitHub pull request linked to a topic through its Work rows (Better
+ * Coding Experience): any `work_versions` row of a `github_pull_request` Work
+ * with that `topicId` links it, so a topic can carry several. The Work is the
+ * only source — nothing here is guessed from the working directory's branch.
+ */
+export interface TopicPullRequestWork {
+ baseBranch?: string;
+ headBranch?: string;
+ /** `owner/repo#number`. */
+ identifier: string;
+ /** Newest version of this Work registered in the topic. */
+ linkedAt: Date;
+ number: number;
+ repoFullName: string;
+ /** Status the agent's own commands left it in (`open`, `draft`, `merged`). */
+ status: string | null;
+ title: string | null;
+ url: string | null;
+ workId: string;
+}
+
+/**
+ * What the GitHub App last reported about a linked pull request. Present only
+ * when an installation the viewer can see tracks the repository — that is the
+ * confirmed source; without it the client probes the execution device.
+ */
+export interface TopicPullRequestScmState {
+ ciStatus: 'failure' | 'pending' | 'success' | 'unknown' | null;
+ isDraft: boolean;
+ mergedAt: Date | null;
+ reviewDecision: 'approved' | 'changes_requested' | 'review_required' | null;
+ state: 'closed' | 'merged' | 'open';
+ title: string | null;
+ updatedAt: Date;
+}
+
+export interface TopicPullRequestItem extends TopicPullRequestWork {
+ scm: TopicPullRequestScmState | null;
+}
diff --git a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
index a332dbbf6bc..fd4e6709e8b 100644
--- a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
@@ -23,12 +23,21 @@ vi.mock('react-i18next', () => ({
vi.mock('@/const/version', () => ({ isDesktop: false }));
+const labMock = vi.hoisted(() => ({ betterCoding: false }));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableBetterCodingExperience: () => labMock.betterCoding },
+}));
+
vi.mock('@/features/ChatInput/ControlBar/DirIcon', () => ({
default: ({ size }: { size?: number }) => <span data-size={size} data-testid="dir-icon" />,
}));
afterEach(() => {
vi.clearAllMocks();
+ labMock.betterCoding = false;
});
describe('MetaHoverCard', () => {
@@ -119,4 +128,33 @@ describe('MetaHoverCard', () => {
expect(link).toHaveTextContent('metaCard.pr.merged · #16951 perf(swr): persist activeScopeKey');
expect(screen.getByTitle('#16951 perf(swr): persist activeScopeKey')).toBeInTheDocument();
});
+
+ it('hides the branch-guessed PR under Better Coding Experience', () => {
+ const metadata: ChatTopicMetadata = {
+ workingDirectory: '/repo',
+ workingDirectoryConfig: {
+ git: {
+ branch: 'feat/x',
+ github: {
+ pullRequest: {
+ number: 42,
+ state: 'open',
+ title: 'guessed PR',
+ url: 'https://github.com/lobehub/lobehub/pull/42',
+ },
+ },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ };
+
+ const { rerender } = render(<MetaHoverCard metadata={metadata} title="Topic" />);
+ expect(screen.getByText(/guessed PR/)).toBeInTheDocument();
+
+ labMock.betterCoding = true;
+ rerender(<MetaHoverCard metadata={metadata} title="Topic 2" />);
+ expect(screen.queryByText(/guessed PR/)).not.toBeInTheDocument();
+ expect(screen.getByText('feat/x')).toBeInTheDocument();
+ });
});
diff --git a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx
index 3d9845a23d7..22775df6597 100644
--- a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx
@@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next';
import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
import {
getCiVisual,
@@ -133,7 +135,8 @@ const MetaHoverCard = memo<MetaHoverCardProps>(({ metadata, title, time, topicId
const useFetchTopicLinkedPullRequest = useChatStore((s) => s.useFetchTopicLinkedPullRequest);
useFetchTopicLinkedPullRequest(topicId, metadata);
- const card = getTopicMetaCard(metadata);
+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);
+ const card = getTopicMetaCard(metadata, { hideRecordedPullRequest: betterCoding });
if (!card) return null;
const { repoName, repoType, branch, detached, worktreeName, pullRequest } = card;
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index c30f36e7d1a..b28d1789d39 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -128,7 +128,10 @@ vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: unknown) => unknown) => selector({}),
}));
vi.mock('@/store/user/selectors', () => ({
- labPreferSelectors: { enableGoals: () => goalsEnabledMock.value },
+ labPreferSelectors: {
+ enableBetterCodingExperience: () => false,
+ enableGoals: () => goalsEnabledMock.value,
+ },
userProfileSelectors: { userId: () => currentUserIdMock.value },
}));
vi.mock('@/hooks/useTopicOnlyMine', () => ({ useTopicOnlyMine: () => onlyMineMock.value }));
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 25f962e15fa..eaae8fd3388 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -443,7 +443,11 @@ const TopicItemRow = memo<TopicItemRowProps>(
// Codex-style hover detail card: when the topic carries git context, hovering
// the row reveals a card on the right with repo / branch / worktree / PR / CI —
// keeping the row itself clean.
- const metaCard = useMemo(() => getTopicMetaCard(metadata), [metadata]);
+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);
+ const metaCard = useMemo(
+ () => getTopicMetaCard(metadata, { hideRecordedPullRequest: betterCoding }),
+ [betterCoding, metadata],
+ );
// For default topic (no id)
if (!id) {
diff --git a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
index cf13ad1da43..0497fe0ce45 100644
--- a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
+++ b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
@@ -84,7 +84,14 @@ export const getCiVisual = (status?: DeviceGitPullRequestCiStatus): CiVisual =>
* `workingDirectoryConfig`. Returns `undefined` when the topic carries no git
* context, so the caller can skip the hover card entirely (no probe).
*/
-export const getTopicMetaCard = (metadata: ChatTopicMetadata | undefined) => {
+export const getTopicMetaCard = (
+ metadata: ChatTopicMetadata | undefined,
+ /**
+ * Better Coding Experience: the recorded PR is a branch guess, which the lab
+ * no longer shows — a topic's PRs come from its Work rows instead.
+ */
+ options: { hideRecordedPullRequest?: boolean } = {},
+) => {
const config = metadata?.workingDirectoryConfig;
const git = config?.git;
if (!git) return undefined;
@@ -96,7 +103,9 @@ export const getTopicMetaCard = (metadata: ChatTopicMetadata | undefined) => {
return {
branch: git.branch,
detached: git.detached,
- pullRequest: git.github?.pullRequest ?? undefined,
+ pullRequest: options.hideRecordedPullRequest
+ ? undefined
+ : (git.github?.pullRequest ?? undefined),
repoName: sourcePath ? getWorkingDirectoryName(sourcePath) : undefined,
repoType: getConfigRepoType(config),
worktreeName: isWorktree && effectivePath ? getWorkingDirectoryName(effectivePath) : undefined,
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 958d6299f2c..f05c1818072 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -30,6 +30,7 @@ import { useDraftBranch } from './DraftGit/useDraftBranch';
import { WorktreeToggle } from './DraftGit/WorktreeToggle';
import { gitChipStyles } from './gitChipStyles';
import StaleGitSnapshot from './StaleGitSnapshot';
+import TopicPullRequestChip from './TopicPullRequestChip';
import WorktreeSwitcher from './WorktreeSwitcher';
const styles = stylex.create({
@@ -193,11 +194,13 @@ const GitStatus = memo<GitStatusProps>(
isDraft && draft.selectedBranch && draft.selectedBranch !== branch
? draft.selectedBranch
: undefined;
+ // Under the lab a topic's PRs come from its Work rows (TopicPullRequestChip):
+ // the branch → PR guess is not asked at all.
const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(
deviceId,
path,
syncBranch ?? branch,
- isGithub,
+ isGithub && !betterCoding,
);
// The remaining reads are all disabled once the directory is gone: nothing
// below renders from them in that state, and the diff poll alone would keep
@@ -237,8 +240,9 @@ const GitStatus = memo<GitStatusProps>(
// Until the linked-PR lookup answers for this branch, reuse the PR the topic
// recorded for the same branch so the PR chip doesn't pop in late.
- const pullRequest =
- prData !== undefined
+ const pullRequest = betterCoding
+ ? undefined
+ : prData !== undefined
? prData.pullRequest
: isGithub &&
!syncBranch &&
@@ -368,19 +372,30 @@ const GitStatus = memo<GitStatusProps>(
reviewPatches !== undefined ? liveDiffStats : (cachedDiffStats ?? liveDiffStats);
const hasChanges = diffStats.files > 0;
+ // Better Coding Experience: the topic's linked PRs are server records, so
+ // they stay in the bar (with their last known state) even when the working
+ // directory cannot be read — an offline device, a deleted worktree.
+ const topicPullRequestChip =
+ betterCoding && topicId ? (
+ <TopicPullRequestChip deviceId={deviceId} path={path} topicId={topicId} />
+ ) : null;
+
// Dead directory: the whole live cluster is unreachable, so hand off to the
// snapshot renderer — it shows what the topic recorded and offers the one
// action that can still work (drop the worktree override).
if (isStale) {
return (
- <StaleGitSnapshot
- agentId={agentId}
- git={fallbackGit!}
- isGithub={isGithub}
- path={path}
- sourcePath={sourcePath}
- topicId={topicId}
- />
+ <>
+ <StaleGitSnapshot
+ agentId={agentId}
+ git={betterCoding ? { ...fallbackGit!, github: undefined } : fallbackGit!}
+ isGithub={isGithub}
+ path={path}
+ sourcePath={sourcePath}
+ topicId={topicId}
+ />
+ {topicPullRequestChip}
+ </>
);
}
@@ -411,10 +426,11 @@ const GitStatus = memo<GitStatusProps>(
</Tooltip>
</>
)}
+ {topicPullRequestChip}
</>
);
}
- return null;
+ return topicPullRequestChip;
}
const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;
@@ -622,6 +638,7 @@ const GitStatus = memo<GitStatusProps>(
{outdatedNode}
{worktreeToggleNode}
{diffNode}
+ {topicPullRequestChip}
{pullRequest && (
<>
<div {...stylex.props(gitChipStyles.separator)} />
diff --git a/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx
new file mode 100644
index 00000000000..aeedbb972d6
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx
@@ -0,0 +1,94 @@
+import { DropdownMenu, Icon, Tooltip } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { GitPullRequest } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ getPullRequestState,
+ PR_STATE_VISUAL,
+} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
+import TopicPullRequestProbes from '@/features/TopicPullRequests/TopicPullRequestProbes';
+import { useTopicPullRequests } from '@/features/TopicPullRequests/useTopicPullRequests';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
+
+import { gitChipStyles } from './gitChipStyles';
+
+const styles = stylex.create({
+ extra: { color: 'inherit', fontVariantNumeric: 'tabular-nums', opacity: 0.65 },
+});
+
+interface TopicPullRequestChipProps {
+ deviceId?: string;
+ path: string;
+ topicId: string;
+}
+
+/**
+ * Better Coding Experience: the pull requests the agent's own commands linked
+ * to this topic. Shows the latest one still open (else the latest), plus how
+ * many more; with more than one, a click lists them all. Nothing renders until
+ * a PR is linked.
+ */
+const TopicPullRequestChip = memo<TopicPullRequestChipProps>(({ deviceId, path, topicId }) => {
+ const { t } = useTranslation('device');
+ const { primary, probes, views } = useTopicPullRequests({ deviceId, path, topicId });
+ const extra = views.length - 1;
+
+ const items = useMemo(
+ () =>
+ views.map((view) => {
+ const visual = PR_STATE_VISUAL[getPullRequestState(view)];
+ return {
+ icon: <Icon color={visual.color} icon={visual.icon} size={14} />,
+ key: view.identifier,
+ label: `#${view.number} ${view.title}`,
+ onClick: () => openTrustedExternalUrl(view.url),
+ };
+ }),
+ [views],
+ );
+
+ const probeReads = <TopicPullRequestProbes deviceId={deviceId} path={path} probes={probes} />;
+ if (!primary) return probeReads;
+
+ const chip = (
+ <div
+ {...stylex.props(gitChipStyles.prTrigger)}
+ data-testid="topic-pull-request-chip"
+ role="button"
+ onClick={extra > 0 ? undefined : () => openTrustedExternalUrl(primary.url)}
+ >
+ <Icon icon={GitPullRequest} size={12} />
+ <span>#{primary.number}</span>
+ {extra > 0 && <span {...stylex.props(styles.extra)}>+{extra}</span>}
+ </div>
+ );
+
+ return (
+ <>
+ {probeReads}
+ <div {...stylex.props(gitChipStyles.separator)} />
+ {extra > 0 ? (
+ <DropdownMenu items={items} placement="topLeft">
+ <div>
+ <Tooltip
+ title={t('workingDirectory.topicPullRequestsTooltip', {
+ count: extra,
+ title: primary.title,
+ })}
+ >
+ {chip}
+ </Tooltip>
+ </div>
+ </DropdownMenu>
+ ) : (
+ <Tooltip title={primary.title}>{chip}</Tooltip>
+ )}
+ </>
+ );
+});
+
+TopicPullRequestChip.displayName = 'TopicPullRequestChip';
+
+export default TopicPullRequestChip;
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 705929a04d2..ca7b807fa17 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -1,8 +1,9 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { gitService } from '@/services/git';
+import { useUserStore } from '@/store/user';
import GitStatus from '../GitStatus';
@@ -44,6 +45,12 @@ vi.mock('../WorktreeSwitcher', () => ({
),
}));
+vi.mock('../TopicPullRequestChip', () => ({
+ default: ({ topicId }: { topicId: string }) => (
+ <span data-testid="topic-pull-request-chip">{topicId}</span>
+ ),
+}));
+
vi.mock('../StaleGitSnapshot', () => ({
default: ({ git }: { git: { branch?: string } }) => (
<span data-branch={git.branch} data-testid="stale-git-snapshot" />
@@ -647,3 +654,72 @@ describe('GitStatus', () => {
expect(screen.getByText('fix/remote-review')).toBeInTheDocument();
});
});
+
+describe('GitStatus — Better Coding Experience pull requests', () => {
+ const setLab = (on: boolean) => {
+ const preference = useUserStore.getState().preference;
+ useUserStore.setState({
+ preference: { ...preference, lab: { ...preference.lab, enableBetterCodingExperience: on } },
+ });
+ };
+
+ afterEach(() => setLab(false));
+
+ it('shows the topic PR chip instead of the branch PR, and never asks gh for the branch', () => {
+ setLab(true);
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: {
+ pullRequest: { number: 77, state: 'OPEN', title: 'guessed', url: 'https://x/77' },
+ },
+ mutate: gitHookMocks.mutatePR,
+ });
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId="topic-1" />);
+
+ expect(gitHookMocks.useFetchGitLinkedPR).toHaveBeenCalledWith(
+ undefined,
+ '/repo',
+ 'fix/remote-review',
+ false,
+ );
+ expect(screen.queryByText('#77')).toBeNull();
+ expect(screen.getByTestId('topic-pull-request-chip')).toHaveTextContent('topic-1');
+ });
+
+ it('shows no PR at all on a new conversation', () => {
+ setLab(true);
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId={null} />);
+
+ expect(screen.queryByTestId('topic-pull-request-chip')).toBeNull();
+ });
+
+ it('keeps the branch PR chip without the lab', () => {
+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({
+ data: { pullRequest: { number: 77, state: 'OPEN', title: 'branch', url: 'https://x/77' } },
+ mutate: gitHookMocks.mutatePR,
+ });
+
+ render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId="topic-1" />);
+
+ expect(screen.getByText('#77')).toBeInTheDocument();
+ expect(screen.queryByTestId('topic-pull-request-chip')).toBeNull();
+ });
+
+ it('keeps the topic PR chip while the device cannot be read', () => {
+ setLab(true);
+ deviceStoreMock.devices = [{ deviceId: 'device-1', online: false }];
+ gitHookMocks.useFetchGitBranch.mockReturnValue({
+ data: undefined,
+ error: new Error('offline'),
+ isConfirmed: false,
+ mutate: gitHookMocks.mutateBranch,
+ });
+
+ render(
+ <GitStatus isGithub agentId="agent-1" deviceId="device-1" path="/repo" topicId="topic-1" />,
+ );
+
+ expect(screen.getByTestId('topic-pull-request-chip')).toHaveTextContent('topic-1');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/__tests__/TopicPullRequestChip.test.tsx b/src/features/ChatInput/ControlBar/__tests__/TopicPullRequestChip.test.tsx
new file mode 100644
index 00000000000..a21069d0f66
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/TopicPullRequestChip.test.tsx
@@ -0,0 +1,89 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TopicPullRequestChip from '../TopicPullRequestChip';
+
+const mocks = vi.hoisted(() => ({
+ open: vi.fn(),
+ result: { primary: undefined as any, probes: [] as any[], views: [] as any[] },
+}));
+
+vi.mock('@/features/TopicPullRequests/useTopicPullRequests', () => ({
+ useTopicPullRequests: () => mocks.result,
+}));
+vi.mock('@/features/TopicPullRequests/TopicPullRequestProbes', () => ({
+ default: ({ probes }: { probes: { number: number }[] }) => (
+ <span data-numbers={probes.map((p) => p.number).join(',')} data-testid="probes" />
+ ),
+}));
+vi.mock('@/utils/openTrustedExternalUrl', () => ({ openTrustedExternalUrl: mocks.open }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<any>()),
+ DropdownMenu: ({ children, items }: any) => (
+ <div data-testid="menu">
+ {children}
+ {items.map((item: any) => (
+ <button key={item.key} onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </div>
+ ),
+ Tooltip: ({ children }: any) => children,
+}));
+
+const view = (number: number, state = 'open') => ({
+ identifier: `lobehub/lobehub#${number}`,
+ number,
+ repoFullName: 'lobehub/lobehub',
+ state,
+ title: `PR ${number}`,
+ url: `https://github.com/lobehub/lobehub/pull/${number}`,
+});
+
+describe('TopicPullRequestChip', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('renders only the device probes while no PR is linked', () => {
+ mocks.result = { primary: undefined, probes: [], views: [] };
+ render(<TopicPullRequestChip path="/repo" topicId="t1" />);
+
+ expect(screen.queryByTestId('topic-pull-request-chip')).toBeNull();
+ expect(screen.getByTestId('probes')).toBeInTheDocument();
+ });
+
+ it('opens the only linked PR directly', () => {
+ mocks.result = { primary: view(12), probes: [{ number: 12, version: 1 }], views: [view(12)] };
+ render(<TopicPullRequestChip path="/repo" topicId="t1" />);
+
+ const chip = screen.getByTestId('topic-pull-request-chip');
+ expect(chip).toHaveTextContent('#12');
+ expect(chip).not.toHaveTextContent('+');
+ fireEvent.click(chip);
+ expect(mocks.open).toHaveBeenCalledWith('https://github.com/lobehub/lobehub/pull/12');
+ });
+
+ it('shows the latest open PR plus the count, and lists them all', () => {
+ const views = [view(13, 'merged'), view(12)];
+ mocks.result = {
+ primary: views[1],
+ probes: [
+ { number: 13, version: 1 },
+ { number: 12, version: 1 },
+ ],
+ views,
+ };
+ render(<TopicPullRequestChip path="/repo" topicId="t1" />);
+
+ expect(screen.getByTestId('topic-pull-request-chip')).toHaveTextContent('#12+1');
+ fireEvent.click(screen.getByText('#13 PR 13'));
+ expect(mocks.open).toHaveBeenCalledWith('https://github.com/lobehub/lobehub/pull/13');
+ expect(screen.getByText('#12 PR 12')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx
new file mode 100644
index 00000000000..279547cc611
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx
@@ -0,0 +1,64 @@
+import type { DeviceGitLinkedPullRequest } from '@lobechat/types';
+import { Icon, Tooltip } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ getCiVisual,
+ getPullRequestState,
+ PR_STATE_VISUAL,
+} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
+
+import { shouldShowCiLabel } from './overviewData';
+import { OverviewRow, rowStyles } from './OverviewRow';
+import { sectionStyles } from './sectionStyles';
+
+interface PullRequestRowProps {
+ onClick: () => void;
+ pullRequest: DeviceGitLinkedPullRequest;
+ /** Defaults to `#number title`. */
+ tooltip?: string;
+}
+
+/** One pull request under the repository card's Changes row: state, number, title, CI. */
+const PullRequestRow = memo<PullRequestRowProps>(({ onClick, pullRequest, tooltip }) => {
+ const { t } = useTranslation('chat');
+ const ciStatus = pullRequest.ciStatus;
+ const ci = getCiVisual(ciStatus);
+ const prVisual = PR_STATE_VISUAL[getPullRequestState(pullRequest)];
+
+ return (
+ <Tooltip title={tooltip ?? `#${pullRequest.number} ${pullRequest.title}`}>
+ <div>
+ <OverviewRow
+ icon={prVisual.icon}
+ iconColor={prVisual.color}
+ trailing={
+ <span
+ className={sectionStyles.pill}
+ style={{ background: `color-mix(in srgb, 12%, transparent)`, color: ci.color }}
+ >
+ <Icon icon={ci.icon} size={12} />
+ {shouldShowCiLabel(ciStatus)
+ ? t(
+ `workingPanel.overview.ci.${ciStatus as 'failure' | 'pending'}` as 'workingPanel.overview.ci.failure',
+ )
+ : null}
+ </span>
+ }
+ value={
+ <>
+ <span className={rowStyles.num}>#{pullRequest.number}</span>
+ {pullRequest.title}
+ </>
+ }
+ onClick={onClick}
+ />
+ </div>
+ </Tooltip>
+ );
+});
+
+PullRequestRow.displayName = 'OverviewPullRequestRow';
+
+export default PullRequestRow;
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index e8f4fa32bb5..1cf61db048a 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -11,7 +11,6 @@ import {
Icon,
Skeleton,
toast,
- Tooltip,
} from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import {
@@ -31,16 +30,12 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RingLoadingIcon from '@/components/RingLoading';
-import {
- getCiVisual,
- getPullRequestState,
- PR_STATE_VISUAL,
-} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
import ThreadListSection from '@/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadListSection';
import { TopicBackgroundActivity } from '@/features/BackgroundActivity/TopicSection';
import BranchSwitcher from '@/features/ChatInput/ControlBar/BranchSwitcher';
import WorktreeSwitcher from '@/features/ChatInput/ControlBar/WorktreeSwitcher';
import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';
+import type { TopicPullRequestView } from '@/features/TopicPullRequests/pullRequestView';
import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
import { gitService } from '@/services/git';
import { useAgentStore } from '@/store/agent';
@@ -58,16 +53,17 @@ import { labPreferSelectors } from '@/store/user/selectors';
import GoalSection from '../GoalSection';
import ProgressSection from '../ProgressSection';
+import { toLinkedPullRequest } from '../PullRequest/useSidebarPullRequests';
import DeviceStatusSection from './DeviceStatusSection';
import {
collectChangeStats,
isLinkedWorktreeCheckout,
- shouldShowCiLabel,
shouldShowGitSkeleton,
} from './overviewData';
import OverviewHeader from './OverviewHeader';
import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';
import PortSwitcher from './PortSwitcher';
+import PullRequestRow from './PullRequestRow';
import { sectionStyles } from './sectionStyles';
import { TerminalRow } from './TerminalRow';
@@ -87,10 +83,17 @@ interface OverviewProps {
/** Routes file / git RPCs; empty for "This device", which reads over IPC. */
deviceId?: string;
environmentAvailable: boolean;
+ /** Better Coding Experience: open one of {@link pullRequests}. */
+ onOpenPullRequest?: (pullRequest: TopicPullRequestView) => void;
onOpenTab: (tab: string) => void;
onRefreshPullRequest: () => Promise<unknown>;
/** Parent-owned so the Overview row and the on-demand PR tab cannot disagree. */
pullRequest?: DeviceGitLinkedPullRequest | null;
+ /**
+ * Better Coding Experience: every PR the topic's Work rows link, listed
+ * under Changes in place of the single branch PR.
+ */
+ pullRequests?: TopicPullRequestView[];
repoType?: string;
sourcePath?: string;
/** The bound machine whose live status to show, local desktop included. */
@@ -106,9 +109,11 @@ const Overview = memo<OverviewProps>(
agentId,
deviceId,
environmentAvailable,
+ onOpenPullRequest,
onOpenTab,
onRefreshPullRequest,
pullRequest,
+ pullRequests,
repoType,
sourcePath,
statusDeviceId,
@@ -249,10 +254,6 @@ const Overview = memo<OverviewProps>(
}
}, [deviceId, refreshGit, syncBusy, tDevice, workingDirectory]);
- const ciStatus = pullRequest?.ciStatus;
- const ci = pullRequest ? getCiVisual(ciStatus) : undefined;
- const prVisual = pullRequest ? PR_STATE_VISUAL[getPullRequestState(pullRequest)] : undefined;
-
const showAhead = !!aheadBehind?.hasUpstream && aheadBehind.ahead > 0;
const showBehind = !!aheadBehind?.hasUpstream && aheadBehind.behind > 0;
@@ -279,6 +280,19 @@ const Overview = memo<OverviewProps>(
/>
);
+ // Better Coding Experience PRs are server records: they stay listed with
+ // their last known state even when the working directory cannot be read.
+ const pullRequestRows = pullRequests
+ ? pullRequests.map((view) => (
+ <PullRequestRow
+ key={view.identifier}
+ pullRequest={toLinkedPullRequest(view)}
+ tooltip={`${view.repoFullName}#${view.number} ${view.title}`}
+ onClick={() => onOpenPullRequest?.(view)}
+ />
+ ))
+ : pullRequest && <PullRequestRow pullRequest={pullRequest} onClick={() => onOpenTab('pr')} />;
+
const gitRows = (
<>
{branch &&
@@ -385,36 +399,7 @@ const Overview = memo<OverviewProps>(
onClick={() => onOpenTab('review')}
/>
- {pullRequest && prVisual && ci && (
- <Tooltip title={`#${pullRequest.number} ${pullRequest.title}`}>
- <div>
- <OverviewRow
- icon={prVisual.icon}
- iconColor={prVisual.color}
- trailing={
- <span
- className={sectionStyles.pill}
- style={{ background: `color-mix(in srgb, 12%, transparent)`, color: ci.color }}
- >
- <Icon icon={ci.icon} size={12} />
- {shouldShowCiLabel(ciStatus)
- ? t(
- `workingPanel.overview.ci.${ciStatus as 'failure' | 'pending'}` as 'workingPanel.overview.ci.failure',
- )
- : null}
- </span>
- }
- value={
- <>
- <span className={rowStyles.num}>#{pullRequest.number}</span>
- {pullRequest.title}
- </>
- }
- onClick={() => onOpenTab('pr')}
- />
- </div>
- </Tooltip>
- )}
+ {pullRequestRows}
</>
);
@@ -424,21 +409,24 @@ const Overview = memo<OverviewProps>(
<Skeleton.Text rows={3} />
</div>
) : gitError ? (
- <OverviewRow
- danger
- icon={TriangleAlertIcon}
- iconColor={cssVar.colorError}
- value={t('workingPanel.overview.environmentError')}
- trailing={
- <Button
- icon={<Icon icon={RefreshCwIcon} size={12} />}
- size={'small'}
- onClick={() => void refreshGit()}
- >
- {tCommon('retry')}
- </Button>
- }
- />
+ <>
+ <OverviewRow
+ danger
+ icon={TriangleAlertIcon}
+ iconColor={cssVar.colorError}
+ value={t('workingPanel.overview.environmentError')}
+ trailing={
+ <Button
+ icon={<Icon icon={RefreshCwIcon} size={12} />}
+ size={'small'}
+ onClick={() => void refreshGit()}
+ >
+ {tCommon('retry')}
+ </Button>
+ }
+ />
+ {pullRequests && pullRequestRows}
+ </>
) : (
gitRows
)
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts
index 4d1b6e354ae..175f7191a2a 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts
@@ -1,7 +1,12 @@
import type { DeviceGitPullRequestDetail } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { type MergeDockInput, PR_KEYS, resolveMergeDock } from '../mergeDockData';
+import {
+ checkoutPublishesTo as publishesTo,
+ type MergeDockInput,
+ PR_KEYS,
+ resolveMergeDock,
+} from '../mergeDockData';
const makeDetail = (
overrides: Partial<DeviceGitPullRequestDetail> = {},
@@ -392,3 +397,19 @@ describe('resolveMergeDock', () => {
});
});
});
+
+describe('checkoutPublishesTo', () => {
+ it('matches the PR head by the tracking ref or the push target', () => {
+ expect(publishesTo({ upstream: 'origin/feat/x' }, 'feat/x')).toBe(true);
+ expect(publishesTo({ pushTarget: 'origin/feat/x', upstream: 'origin/canary' }, 'feat/x')).toBe(
+ true,
+ );
+ });
+
+ it('refuses a checkout that publishes another branch', () => {
+ expect(publishesTo({ pushTarget: 'origin/feat/b', upstream: 'origin/feat/b' }, 'feat/a')).toBe(
+ false,
+ );
+ expect(publishesTo({}, 'feat/a')).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts
new file mode 100644
index 00000000000..e96eb055037
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts
@@ -0,0 +1,111 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useSidebarPullRequests } from '../useSidebarPullRequests';
+
+const mocks = vi.hoisted(() => ({
+ betterCoding: true,
+ legacy: vi.fn(),
+ linked: {
+ enabled: true,
+ primary: undefined as any,
+ probes: [] as any[],
+ views: [] as any[],
+ },
+ refresh: vi.fn(),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableBetterCodingExperience: () => mocks.betterCoding },
+}));
+vi.mock('@/features/TopicPullRequests/useTopicPullRequests', () => ({
+ useTopicPullRequests: () => mocks.linked,
+}));
+vi.mock('@/services/work', () => ({ workService: { refreshTopicPullRequests: mocks.refresh } }));
+vi.mock('../useLinkedPullRequest', () => ({
+ useLinkedPullRequest: (params: unknown) => {
+ mocks.legacy(params);
+ return { confirmed: true, pullRequest: { number: 1 }, refresh: vi.fn() };
+ },
+}));
+
+const view = (number: number, extra: Record<string, unknown> = {}) => ({
+ confirmed: true,
+ identifier: `a/b#${number}`,
+ isDraft: false,
+ localDetail: true,
+ number,
+ repoFullName: 'a/b',
+ state: 'open',
+ title: `PR ${number}`,
+ url: `https://github.com/a/b/pull/${number}`,
+ ...extra,
+});
+
+const PARAMS = {
+ available: true,
+ gitPath: '/repo',
+ isGithub: true,
+ topicId: 't1',
+ workingDirectory: '/repo',
+};
+
+describe('useSidebarPullRequests', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.betterCoding = true;
+ mocks.linked = { enabled: true, primary: undefined, probes: [], views: [] };
+ });
+
+ it('keeps the branch PR path untouched without the lab', () => {
+ mocks.betterCoding = false;
+ mocks.linked = { ...mocks.linked, enabled: false };
+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));
+
+ expect(mocks.legacy).toHaveBeenCalledWith(PARAMS);
+ expect(result.current.pullRequest).toEqual({ number: 1 });
+ expect(result.current.pullRequests).toBeUndefined();
+ });
+
+ it('never asks for the branch PR under the lab', () => {
+ renderHook(() => useSidebarPullRequests(PARAMS));
+
+ expect(mocks.legacy).toHaveBeenCalledWith(
+ expect.objectContaining({ gitPath: undefined, isGithub: false, snapshot: undefined }),
+ );
+ });
+
+ it('lists every linked PR and opens the picked one in the tab', () => {
+ const views = [view(3), view(2), view(9, { localDetail: false })];
+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };
+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));
+
+ expect(result.current.pullRequests).toHaveLength(3);
+ expect(result.current.pullRequest?.number).toBe(3);
+
+ let opened: boolean | undefined;
+ act(() => {
+ opened = result.current.pickPullRequest?.(views[1] as any);
+ });
+ expect(opened).toBe(true);
+ expect(result.current.pullRequest?.number).toBe(2);
+ // A PR in another repository cannot open in the pane; the caller opens GitHub.
+ expect(result.current.pickPullRequest?.(views[2] as any)).toBe(false);
+ });
+
+ it('locks mutations until the PR is confirmed', () => {
+ const views = [view(3, { confirmed: false })];
+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };
+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));
+
+ expect(result.current.confirmed).toBe(false);
+ result.current.onRetryConfirm?.();
+ expect(mocks.refresh).toHaveBeenCalledWith('t1');
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
index ec2188cd33c..ea49935dfa1 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx
@@ -17,6 +17,7 @@ import { sectionStyles } from '../Overview/sectionStyles';
import { resolvePullRequestActionLock } from './actionLock';
import Header from './Header';
import MergeDock from './MergeDock';
+import { checkoutPublishesTo } from './mergeDockData';
import Sections from './Sections';
import PullRequestSkeleton from './Skeleton';
import { usePullRequestActions } from './usePullRequestActions';
@@ -178,7 +179,13 @@ const PullRequest = memo<PullRequestProps>(
if (!detail) return loadError(fetchError, () => void mutate());
- const local = aheadBehind?.hasUpstream ? { ahead: aheadBehind.ahead } : undefined;
+ // The checkout's unpushed commits belong to this PR only when the checkout
+ // publishes to its head; otherwise "Push N commits" would publish another
+ // branch under this PR (one topic can link several PRs).
+ const local =
+ aheadBehind?.hasUpstream && checkoutPublishesTo(aheadBehind, detail.headRefName)
+ ? { ahead: aheadBehind.ahead }
+ : undefined;
return (
<Flexbox className={styles.root}>
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts b/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts
index 63c8abe8ef2..e1d4f124360 100644
--- a/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts
@@ -361,3 +361,18 @@ export const resolveMergeDock = ({ detail, local, ui }: MergeDockInput): MergeDo
status,
};
};
+
+/** `origin/feat/x` → `feat/x`. */
+const remoteBranch = (ref?: string) => ref?.replace(/^[^/]+\//, '');
+
+/**
+ * Whether the working checkout's unpushed commits go to this PR's head — by
+ * its tracking ref or by the ref the push action targets. A topic can link
+ * several PRs, so the pane may show one the checkout is not on.
+ */
+export const checkoutPublishesTo = (
+ aheadBehind: { pushTarget?: string; upstream?: string },
+ headRefName: string,
+) =>
+ remoteBranch(aheadBehind.upstream) === headRefName ||
+ remoteBranch(aheadBehind.pushTarget) === headRefName;
diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts
new file mode 100644
index 00000000000..5f2a722480d
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts
@@ -0,0 +1,80 @@
+import type { DeviceGitLinkedPullRequest } from '@lobechat/types';
+import { useCallback, useMemo, useState } from 'react';
+
+import type { TopicPullRequestView } from '@/features/TopicPullRequests/pullRequestView';
+import { useTopicPullRequests } from '@/features/TopicPullRequests/useTopicPullRequests';
+import { workService } from '@/services/work';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import { type PullRequestSnapshot, useLinkedPullRequest } from './useLinkedPullRequest';
+
+export const toLinkedPullRequest = (view: TopicPullRequestView): DeviceGitLinkedPullRequest => ({
+ ...(view.ciStatus ? { ciStatus: view.ciStatus } : {}),
+ isDraft: view.isDraft,
+ mergedAt: view.mergedAt ?? null,
+ number: view.number,
+ state: view.state,
+ title: view.title,
+ url: view.url,
+});
+
+/**
+ * The pull request(s) the Working Sidebar shows. Without Better Coding
+ * Experience: the PR linked to the working directory's branch, exactly as
+ * before. With it: every PR the topic's Work rows link (Overview lists them
+ * all), and the PR tab shows the one picked there — only among PRs the device
+ * read in the working directory's own repository, since the pane reads that
+ * number in that directory. Mutations stay locked until the GitHub App or this
+ * session's device read confirmed the PR.
+ */
+export const useSidebarPullRequests = (params: {
+ available: boolean;
+ deviceId?: string;
+ gitPath?: string;
+ isGithub: boolean;
+ snapshot?: PullRequestSnapshot;
+ topicId?: string | null;
+ workingDirectory?: string;
+}) => {
+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);
+ // The branch → PR guess is not even asked under the lab.
+ const legacy = useLinkedPullRequest(
+ betterCoding ? { ...params, gitPath: undefined, isGithub: false, snapshot: undefined } : params,
+ );
+ const linked = useTopicPullRequests({
+ deviceId: params.deviceId,
+ path: params.available ? params.workingDirectory : undefined,
+ topicId: params.topicId,
+ });
+ const [picked, setPicked] = useState<string>();
+
+ const openable = useMemo(() => linked.views.filter((view) => view.localDetail), [linked.views]);
+ const selected =
+ openable.find((view) => view.identifier === picked) ??
+ (linked.primary?.localDetail ? linked.primary : openable[0]);
+
+ const refresh = useCallback(
+ () => workService.refreshTopicPullRequests(params.topicId),
+ [params.topicId],
+ );
+
+ if (!linked.enabled) {
+ return { ...legacy, pickPullRequest: undefined, probes: [], pullRequests: undefined };
+ }
+
+ return {
+ confirmError: undefined,
+ confirmed: !!selected?.confirmed,
+ onRetryConfirm: () => void refresh(),
+ /** Open a listed PR: in the PR tab when the pane can read it, else on GitHub. */
+ pickPullRequest: (view: TopicPullRequestView) => {
+ setPicked(view.identifier);
+ return view.localDetail;
+ },
+ probes: linked.probes,
+ pullRequest: selected ? toLinkedPullRequest(selected) : undefined,
+ pullRequests: linked.views,
+ refresh,
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 5e164034812..ce830885566 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -48,6 +48,7 @@ import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';
import { getPortalViewWidth } from '@/features/Portal/portalWidth';
import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';
import RightPanel from '@/features/RightPanel';
+import TopicPullRequestProbes from '@/features/TopicPullRequests/TopicPullRequestProbes';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
@@ -67,6 +68,7 @@ import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';
import DeferredSkeleton from './DeferredSkeleton';
@@ -89,7 +91,7 @@ import Overview from './Overview';
import { getStatusDeviceId } from './Overview/overviewData';
import OverviewSlot from './OverviewSlot';
import PullRequestSidebarTab from './PullRequest/SidebarTab';
-import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';
+import { useSidebarPullRequests } from './PullRequest/useSidebarPullRequests';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
import { TopicSearchPane } from './Search';
@@ -408,15 +410,20 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
repoType === 'github' || (!repoType && !!snapshotConfig?.git?.github?.pullRequest);
const gitPath = filesystemEnvironmentAvailable && isGithub ? workingDirectory : undefined;
const {
+ pickPullRequest,
+ probes: pullRequestProbes,
pullRequest,
+ pullRequests,
refresh: refreshPullRequest,
...pullRequestLink // confirmed, confirmError, onRetryConfirm
- } = useLinkedPullRequest({
+ } = useSidebarPullRequests({
available: filesystemEnvironmentAvailable && !!workingDirectory,
deviceId: remoteDeviceId,
gitPath,
isGithub,
snapshot: snapshotConfig?.git,
+ topicId,
+ workingDirectory,
});
const paramsAvailable = !isHetero;
// The in-app browser pages are renderer-retained Electron webviews — desktop only.
@@ -905,12 +912,18 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
deviceId={remoteDeviceId}
environmentAvailable={filesystemEnvironmentAvailable}
pullRequest={pullRequest}
+ pullRequests={pullRequests}
repoType={environmentRepoType}
sourcePath={sourceWorkingDirectory}
statusDeviceId={getStatusDeviceId(effectiveTarget, agencyConfig?.boundDeviceId)}
workingDirectory={environmentWorkingDirectory}
onOpenTab={openTab}
onRefreshPullRequest={refreshPullRequest}
+ onOpenPullRequest={
+ pickPullRequest &&
+ ((view) =>
+ pickPullRequest(view) ? openTab('pr') : openTrustedExternalUrl(view.url))
+ }
/>
</Flexbox>
</m.div>
@@ -923,6 +936,11 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
return (
<>
{overviewPanel}
+ <TopicPullRequestProbes
+ deviceId={remoteDeviceId}
+ path={environmentWorkingDirectory}
+ probes={pullRequestProbes}
+ />
<RightPanel
collapseThreshold={320}
defaultWidth={renderWidth}
diff --git a/src/features/TopicPullRequests/TopicPullRequestProbes.test.tsx b/src/features/TopicPullRequests/TopicPullRequestProbes.test.tsx
new file mode 100644
index 00000000000..da4d5d15d7d
--- /dev/null
+++ b/src/features/TopicPullRequests/TopicPullRequestProbes.test.tsx
@@ -0,0 +1,44 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TopicPullRequestProbes from './TopicPullRequestProbes';
+
+const mocks = vi.hoisted(() => ({ mutate: vi.fn(), read: vi.fn() }));
+
+vi.mock('@/store/device', () => ({
+ useFetchGitPullRequestDetail: (...args: unknown[]) => {
+ mocks.read(...args);
+ return { mutate: mocks.mutate };
+ },
+}));
+
+describe('TopicPullRequestProbes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('reads each linked PR on the device without polling', () => {
+ render(
+ <TopicPullRequestProbes deviceId="d1" path="/repo" probes={[{ number: 3, version: 1 }]} />,
+ );
+
+ expect(mocks.read).toHaveBeenCalledWith('d1', '/repo', 3, { active: false });
+ expect(mocks.mutate).not.toHaveBeenCalled();
+ });
+
+ it('re-reads a PR as soon as the topic links it again (e.g. the agent merged it)', () => {
+ const { rerender } = render(
+ <TopicPullRequestProbes path="/repo" probes={[{ number: 3, version: 1 }]} />,
+ );
+ rerender(<TopicPullRequestProbes path="/repo" probes={[{ number: 3, version: 2 }]} />);
+
+ expect(mocks.mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads nothing without a working directory', () => {
+ render(<TopicPullRequestProbes probes={[{ number: 3, version: 1 }]} />);
+
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/TopicPullRequests/TopicPullRequestProbes.tsx b/src/features/TopicPullRequests/TopicPullRequestProbes.tsx
new file mode 100644
index 00000000000..b62f9bfadbc
--- /dev/null
+++ b/src/features/TopicPullRequests/TopicPullRequestProbes.tsx
@@ -0,0 +1,60 @@
+import { memo, useEffect, useRef } from 'react';
+
+import { useFetchGitPullRequestDetail } from '@/store/device';
+
+/** A linked PR to read on the device; `version` changes whenever the topic touches it again. */
+export interface TopicPullRequestProbe {
+ number: number;
+ version: number;
+}
+
+interface ProbeProps extends TopicPullRequestProbe {
+ deviceId?: string;
+ path: string;
+}
+
+/**
+ * One `gh pr view <n>` read on the execution device. Persisted by the git
+ * review replica, so an offline device still paints the last known state.
+ * Inactive: no polling — the open sidebar PR tab polls the one it shows. A new
+ * link version (the agent merged it, pushed to it…) re-reads it at once, so the
+ * device answer never lags behind what the agent just did.
+ */
+const Probe = memo<ProbeProps>(({ deviceId, number, path, version }) => {
+ const { mutate } = useFetchGitPullRequestDetail(deviceId, path, number, { active: false });
+ const seen = useRef(version);
+
+ useEffect(() => {
+ if (seen.current === version) return;
+ seen.current = version;
+ void mutate();
+ }, [mutate, version]);
+
+ return null;
+});
+
+Probe.displayName = 'TopicPullRequestProbe';
+
+interface TopicPullRequestProbesProps {
+ deviceId?: string;
+ path?: string;
+ probes: TopicPullRequestProbe[];
+}
+
+/**
+ * Reads the device state of linked pull requests. Renders nothing;
+ * `useTopicPullRequests` picks the answers up.
+ */
+const TopicPullRequestProbes = memo<TopicPullRequestProbesProps>(({ deviceId, path, probes }) =>
+ path ? (
+ <>
+ {probes.map((probe) => (
+ <Probe deviceId={deviceId} key={probe.number} path={path} {...probe} />
+ ))}
+ </>
+ ) : null,
+);
+
+TopicPullRequestProbes.displayName = 'TopicPullRequestProbes';
+
+export default TopicPullRequestProbes;
diff --git a/src/features/TopicPullRequests/pullRequestView.test.ts b/src/features/TopicPullRequests/pullRequestView.test.ts
new file mode 100644
index 00000000000..435bfffdabe
--- /dev/null
+++ b/src/features/TopicPullRequests/pullRequestView.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from 'vitest';
+
+import { pickPrimaryPullRequest, resolvePullRequestView, rollupChecks } from './pullRequestView';
+
+const item = (number: number, overrides: Record<string, unknown> = {}) =>
+ ({
+ identifier: `lobehub/lobehub#${number}`,
+ linkedAt: new Date(),
+ number,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ status: 'open',
+ title: `PR ${number}`,
+ url: `https://github.com/lobehub/lobehub/pull/${number}`,
+ workId: `wk-${number}`,
+ ...overrides,
+ }) as any;
+
+const detail = (overrides: Record<string, unknown> = {}) =>
+ ({
+ checks: [{ name: 'ci', required: true, status: 'pending' }],
+ isDraft: false,
+ repo: { name: 'lobehub', owner: 'lobehub' },
+ state: 'merged',
+ title: 'From device',
+ url: 'https://github.com/lobehub/lobehub/pull/1',
+ ...overrides,
+ }) as any;
+
+describe('resolvePullRequestView', () => {
+ it('prefers the GitHub App state and marks it confirmed', () => {
+ const view = resolvePullRequestView(
+ item(1, {
+ scm: { ciStatus: 'failure', isDraft: false, mergedAt: null, state: 'open', title: 'App' },
+ }),
+ { confirmed: false, detail: detail() },
+ );
+ expect(view).toMatchObject({
+ ciStatus: 'failure',
+ confirmed: true,
+ state: 'open',
+ title: 'App',
+ });
+ });
+
+ it('uses the device answer only for the same repository', () => {
+ expect(resolvePullRequestView(item(1), { confirmed: true, detail: detail() })).toMatchObject({
+ ciStatus: 'pending',
+ confirmed: true,
+ state: 'merged',
+ title: 'From device',
+ });
+ const other = resolvePullRequestView(item(1), {
+ confirmed: true,
+ detail: detail({ repo: { name: 'other', owner: 'x' } }),
+ });
+ expect(other).toMatchObject({ confirmed: false, state: 'open', title: 'PR 1' });
+ });
+
+ it('falls back to the status the agent commands recorded', () => {
+ expect(resolvePullRequestView(item(2, { status: 'draft' }))).toMatchObject({
+ confirmed: false,
+ isDraft: true,
+ state: 'open',
+ });
+ expect(resolvePullRequestView(item(3, { status: 'merged' })).state).toBe('merged');
+ });
+});
+
+describe('pickPrimaryPullRequest', () => {
+ it('names the latest open PR, else the latest one', () => {
+ const merged = resolvePullRequestView(item(1, { status: 'merged' }));
+ const open = resolvePullRequestView(item(2));
+ expect(pickPrimaryPullRequest([merged, open])?.number).toBe(2);
+ expect(pickPrimaryPullRequest([merged])?.number).toBe(1);
+ expect(pickPrimaryPullRequest([])).toBeUndefined();
+ });
+});
+
+describe('rollupChecks', () => {
+ it('rolls checks up to failure, pending or success', () => {
+ expect(rollupChecks([])).toBeUndefined();
+ expect(rollupChecks([{ status: 'success' }, { status: 'failure' }] as any)).toBe('failure');
+ expect(rollupChecks([{ status: 'success' }, { status: 'pending' }] as any)).toBe('pending');
+ expect(rollupChecks([{ status: 'success' }, { status: 'skipped' }] as any)).toBe('success');
+ });
+});
+
+describe('resolvePullRequestView · localDetail', () => {
+ it('marks a PR openable in the sidebar only when the device read its repository', () => {
+ const scm = { ciStatus: null, isDraft: false, mergedAt: null, state: 'open', title: 'App' };
+ expect(
+ resolvePullRequestView(item(1, { scm }), { confirmed: true, detail: detail() }).localDetail,
+ ).toBe(true);
+ expect(
+ resolvePullRequestView(item(1, { scm }), {
+ confirmed: true,
+ detail: detail({ repo: { name: 'other', owner: 'x' } }),
+ }).localDetail,
+ ).toBe(false);
+ expect(resolvePullRequestView(item(1, { scm })).localDetail).toBe(false);
+ });
+});
diff --git a/src/features/TopicPullRequests/pullRequestView.ts b/src/features/TopicPullRequests/pullRequestView.ts
new file mode 100644
index 00000000000..bc11a7a5503
--- /dev/null
+++ b/src/features/TopicPullRequests/pullRequestView.ts
@@ -0,0 +1,118 @@
+import type {
+ DeviceGitPullRequestCheck,
+ DeviceGitPullRequestCiStatus,
+ DeviceGitPullRequestDetail,
+ TopicPullRequestItem,
+} from '@lobechat/types';
+
+import type { PullRequestState } from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
+
+/**
+ * One linked pull request as the UI shows it, resolved from the best source
+ * at hand: the GitHub App (confirmed), this session's device answer
+ * (confirmed), the device answer persisted from an earlier session (last
+ * known), or the status the agent's own commands left on the Work row.
+ */
+export interface TopicPullRequestView {
+ ciStatus?: DeviceGitPullRequestCiStatus;
+ /** Confirmed by the GitHub App or by the device in this session. */
+ confirmed: boolean;
+ identifier: string;
+ isDraft: boolean;
+ /** A detail read from the execution device exists (it shares the working directory's repo). */
+ localDetail: boolean;
+ mergedAt?: string | null;
+ number: number;
+ repoFullName: string;
+ state: PullRequestState;
+ title: string;
+ url: string;
+}
+
+/** Device detail for a number, with whether this session confirmed it. */
+export interface DevicePullRequestRead {
+ confirmed: boolean;
+ detail: DeviceGitPullRequestDetail;
+}
+
+const FAILING_CHECKS = new Set<DeviceGitPullRequestCheck['status']>(['failure']);
+
+export const rollupChecks = (
+ checks: DeviceGitPullRequestCheck[],
+): DeviceGitPullRequestCiStatus | undefined => {
+ if (checks.length === 0) return undefined;
+ if (checks.some((check) => FAILING_CHECKS.has(check.status))) return 'failure';
+ if (checks.some((check) => check.status === 'pending')) return 'pending';
+ return 'success';
+};
+
+/**
+ * `gh pr view <n>` runs in the working directory, so it reads that number in
+ * the directory's own repository — which is only the linked PR when the
+ * repositories agree.
+ */
+export const isSameRepository = (detail: DeviceGitPullRequestDetail, repoFullName: string) =>
+ `${detail.repo.owner}/${detail.repo.name}`.toLowerCase() === repoFullName.toLowerCase();
+
+const fallbackUrl = (item: TopicPullRequestItem) =>
+ item.url ?? `https://github.com/${item.repoFullName}/pull/${item.number}`;
+
+export const resolvePullRequestView = (
+ item: TopicPullRequestItem,
+ device?: DevicePullRequestRead,
+): TopicPullRequestView => {
+ const base = {
+ identifier: item.identifier,
+ number: item.number,
+ repoFullName: item.repoFullName,
+ url: fallbackUrl(item),
+ };
+
+ const sameRepo = !!device && isSameRepository(device.detail, item.repoFullName);
+
+ if (item.scm) {
+ return {
+ ...base,
+ ciStatus: item.scm.ciStatus ?? undefined,
+ confirmed: true,
+ isDraft: item.scm.isDraft,
+ localDetail: sameRepo,
+ mergedAt: item.scm.mergedAt ? new Date(item.scm.mergedAt).toISOString() : null,
+ state: item.scm.state,
+ title: item.scm.title ?? item.title ?? `#${item.number}`,
+ };
+ }
+
+ if (device && sameRepo) {
+ const { detail } = device;
+ return {
+ ...base,
+ ciStatus: rollupChecks(detail.checks ?? []),
+ confirmed: device.confirmed,
+ isDraft: detail.isDraft,
+ localDetail: true,
+ mergedAt: detail.mergedAt ?? null,
+ state: detail.state,
+ title: detail.title,
+ url: detail.url || base.url,
+ };
+ }
+
+ const status = item.status?.toLowerCase();
+ return {
+ ...base,
+ confirmed: false,
+ isDraft: status === 'draft',
+ localDetail: false,
+ state: status === 'merged' ? 'merged' : status === 'closed' ? 'closed' : 'open',
+ title: item.title ?? `#${item.number}`,
+ };
+};
+
+/**
+ * The PR the control bar names: the most recently linked one still open,
+ * otherwise the most recently linked one. Views keep the server's order
+ * (latest link first).
+ */
+export const pickPrimaryPullRequest = (views: TopicPullRequestView[]) =>
+ views.find((view) => view.state === 'open') ?? views[0];
diff --git a/src/features/TopicPullRequests/useTopicPullRequests.ts b/src/features/TopicPullRequests/useTopicPullRequests.ts
new file mode 100644
index 00000000000..6c6ddcc45fb
--- /dev/null
+++ b/src/features/TopicPullRequests/useTopicPullRequests.ts
@@ -0,0 +1,76 @@
+import { useMemo } from 'react';
+
+import { gitPullRequestKey } from '@/store/device/gitReview/projection';
+import { useGitReviewStore } from '@/store/device/gitReview/store';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+import { useWorkStore, workActions, workSelectors } from '@/store/work';
+
+import {
+ pickPrimaryPullRequest,
+ resolvePullRequestView,
+ type TopicPullRequestView,
+} from './pullRequestView';
+import type { TopicPullRequestProbe } from './TopicPullRequestProbes';
+
+export interface UseTopicPullRequestsParams {
+ /** Execution device of the working directory; omitted for this machine. */
+ deviceId?: string;
+ /** Working directory the device answers `gh pr view` in; omitted → no device read. */
+ path?: string;
+ topicId?: string | null;
+}
+
+export interface TopicPullRequests {
+ /** Under Better Coding Experience only; false means "show the old surfaces". */
+ enabled: boolean;
+ primary?: TopicPullRequestView;
+ /**
+ * Numbers to read on the execution device (mount {@link TopicPullRequestProbes}):
+ * all of them, since only the device says which ones live in the working
+ * directory's repository — the ones the sidebar PR pane can open.
+ */
+ probes: TopicPullRequestProbe[];
+ views: TopicPullRequestView[];
+}
+
+/**
+ * The pull requests a topic's Work rows link (Better Coding Experience), each
+ * resolved to a displayable state. Without the lab — or before a topic exists
+ * (new conversation) — nothing is read and the list is empty.
+ */
+export const useTopicPullRequests = ({
+ deviceId,
+ path,
+ topicId,
+}: UseTopicPullRequestsParams): TopicPullRequests => {
+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);
+ const activeTopicId = betterCoding && topicId ? topicId : undefined;
+
+ workActions.useFetchTopicPullRequests(activeTopicId ? { topicId: activeTopicId } : null);
+ const items = useWorkStore(workSelectors.topicPullRequests(activeTopicId));
+
+ const detailMap = useGitReviewStore((s) => s.gitPullRequestDetailMap);
+ const detailEntries = useGitReviewStore((s) => s.gitPullRequestDetailReplica.entries);
+
+ return useMemo(() => {
+ const list = items ?? [];
+ const views = list.map((item) => {
+ if (!path) return resolvePullRequestView(item);
+ const key = gitPullRequestKey({ deviceId, number: item.number, path });
+ const detail = detailMap[key]?.value?.detail;
+ return resolvePullRequestView(
+ item,
+ detail ? { confirmed: detailEntries[key]?.source === 'server', detail } : undefined,
+ );
+ });
+ return {
+ enabled: betterCoding,
+ probes: path
+ ? list.map((item) => ({ number: item.number, version: new Date(item.linkedAt).getTime() }))
+ : [],
+ primary: pickPrimaryPullRequest(views),
+ views,
+ };
+ }, [betterCoding, detailEntries, detailMap, deviceId, items, path]);
+};
diff --git a/src/services/work.test.ts b/src/services/work.test.ts
index 1035c7d9a42..cd60de482d3 100644
--- a/src/services/work.test.ts
+++ b/src/services/work.test.ts
@@ -20,6 +20,9 @@ vi.mock('@/libs/trpc/client', () => ({
}));
/** A transcript sync key of `topicId` (the replica's default `replica:sync` shape). */
+const topicPullRequestsSync = (topicId: string) =>
+ replicaKeys.sync('topicPullRequests', 1, cacheScope.get(), topicId, { topicId });
+
const transcriptSync = (topicId: string) =>
replicaKeys.sync('conversationMessages', 1, cacheScope.get(), `p:${topicId}`, {
agentId: 'a1',
@@ -109,7 +112,7 @@ describe('workService.refreshConversation', () => {
it('refreshes messages, history, and mounted version timelines once per operation', async () => {
await workService.refreshConversation('t1', 'th1');
- expect(mutate).toHaveBeenCalledTimes(3);
+ expect(mutate).toHaveBeenCalledTimes(4);
expect(mutate).toHaveBeenCalledWith(workKeys.conversation('t1', 'th1'));
const matchers = mutate.mock.calls
@@ -125,7 +128,7 @@ describe('workService.refreshConversationViews', () => {
it('refreshes the conversation history key and the mounted version timelines', async () => {
await workService.refreshConversationViews('t1', 'th1');
- expect(mutate).toHaveBeenCalledTimes(2);
+ expect(mutate).toHaveBeenCalledTimes(3);
// History list: exact conversation key.
expect(mutate).toHaveBeenCalledWith(workKeys.conversation('t1', 'th1'));
// Expanded version timelines: a matcher over the `work:versions` root.
@@ -133,6 +136,10 @@ describe('workService.refreshConversationViews', () => {
expect(typeof versionMatcher).toBe('function');
expect(versionMatcher(workKeys.versions('w1'))).toBe(true);
expect(versionMatcher(workKeys.conversation('t1', 'th1'))).toBe(false);
+ // The topic's linked pull requests (Better Coding Experience) ride the same scan.
+ const prMatcher = mutate.mock.calls[2][0] as (key: unknown) => boolean;
+ expect(prMatcher(topicPullRequestsSync('t1'))).toBe(true);
+ expect(prMatcher(topicPullRequestsSync('t2'))).toBe(false);
});
it('normalizes a missing threadId to null in the conversation key', async () => {
diff --git a/src/services/work.ts b/src/services/work.ts
index dd689aec80b..b753935d7f7 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -5,6 +5,7 @@ import type {
RegisterDocumentWorkParams,
RegisterSkillToolResultWorkParams,
RegisterTaskWorkParams,
+ TopicPullRequestItem,
WorkItem,
WorkListItem,
WorkSkillProvider,
@@ -15,10 +16,12 @@ import type {
WorkVisibility,
} from '@lobechat/types';
+import { revalidateReplica } from '@/libs/replica';
import { mutate } from '@/libs/swr';
import { matchDomain, workKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
import { revalidateConversationMessages } from '@/services/message/replica';
+import { topicPullRequestsResource } from '@/store/work/projection';
/** One cursor page of the workspace-wide Work list (resource page 产物 gallery). */
export interface WorkSummaryPage {
@@ -128,6 +131,34 @@ class WorkService {
}): Promise<{ failed: number; registered: number; rootOperationId: string | null }> =>
lambdaClient.work.registerShellWorksForRun.mutate(params);
+ /** Better Coding Experience: the pull requests a topic's Work rows link, with App state. */
+ listTopicPullRequests = async (topicId: string): Promise<TopicPullRequestItem[]> =>
+ lambdaClient.work.listTopicPullRequests.query({ topicId });
+
+ /**
+ * Better Coding Experience: link the pull requests a `git push` tool call
+ * updated. `pullRequests` is the execution device's `gh pr list --head`
+ * answer; the server re-reads the push itself and prefers the GitHub App.
+ */
+ linkPushedPullRequests = async (params: {
+ pullRequests: {
+ headRefName: string;
+ isDraft?: boolean;
+ number: number;
+ state?: string;
+ title?: string;
+ url: string;
+ }[];
+ toolCallId: string;
+ topicId: string;
+ }) => lambdaClient.work.linkPushedPullRequests.mutate(params);
+
+ /** Revalidate a topic's linked pull requests (mounted reads only). */
+ refreshTopicPullRequests = async (topicId?: string | null) => {
+ if (!topicId) return;
+ await revalidateReplica(topicPullRequestsResource, topicId);
+ };
+
/**
* Invalidate everything a Work mutation can change for a conversation:
* - the topic's transcript syncs, since Work summaries (in-message chips
@@ -197,6 +228,8 @@ class WorkService {
await Promise.all([
mutate(workKeys.conversation(topicId, threadId ?? null)),
mutate((key) => Array.isArray(key) && key[0] === workKeys.versions.root),
+ // A run's gh / push commands link pull requests through the same scan.
+ this.refreshTopicPullRequests(topicId),
]);
};
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
index 041c4b08090..02192769ee6 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts
@@ -77,6 +77,13 @@ vi.mock('../../../../topic/selectors', () => ({
},
}));
+const labMocks = vi.hoisted(() => ({ betterCoding: false }));
+
+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableBetterCodingExperience: () => labMocks.betterCoding },
+}));
+
const PR = {
ciStatus: 'pending' as const,
number: 123,
@@ -104,6 +111,7 @@ const makeGet = () => {
beforeEach(() => {
vi.clearAllMocks();
+ labMocks.betterCoding = false;
mockConstEnv.isDesktop = true;
env.currentDeviceId = undefined;
env.targetDeviceId = undefined;
@@ -240,3 +248,59 @@ describe('snapshotTopicWorkingDirGit', () => {
expect(updateTopicMetadata).not.toHaveBeenCalled();
});
});
+
+describe('snapshotTopicWorkingDirGit — Better Coding Experience', () => {
+ beforeEach(() => {
+ labMocks.betterCoding = true;
+ });
+
+ it('records the branch and its remote ref without asking gh for a PR', async () => {
+ topicMocks.getTopicById.mockReturnValue(githubTopic);
+ gitMocks.getGitBranch.mockResolvedValue({
+ branch: 'fix/remote-review',
+ detached: false,
+ upstream: { branch: 'fix/remote-review', remote: 'origin' },
+ });
+ const { get, updateTopicMetadata } = makeGet();
+
+ await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(gitMocks.getLinkedPullRequest).not.toHaveBeenCalled();
+ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'fix/remote-review',
+ isWorktree: false,
+ upstream: { branch: 'fix/remote-review', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('drops a recorded PR once the branch moved, keeps it while it stays', async () => {
+ const recorded = {
+ metadata: {
+ workingDirectoryConfig: {
+ git: { branch: 'fix/remote-review', github: { pullRequest: PR } },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ };
+ topicMocks.getTopicById.mockReturnValue(recorded);
+ const same = makeGet();
+ await snapshotTopicWorkingDirGit(same.get, { agentId: 'agent-1', topicId: 'topic-1' });
+ expect(same.updateTopicMetadata.mock.calls[0]?.[1].workingDirectoryConfig.git.github).toEqual({
+ pullRequest: PR,
+ });
+
+ gitMocks.getGitBranch.mockResolvedValue({ branch: 'feat/next', detached: false });
+ const moved = makeGet();
+ await snapshotTopicWorkingDirGit(moved.get, { agentId: 'agent-1', topicId: 'topic-1' });
+ expect(
+ moved.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git,
+ ).not.toHaveProperty('github');
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index bec6d42cee4..3080158ad8d 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 { t } from 'i18next';
import { LOADING_FLAT } from '@/const/message';
+import { workService } from '@/services/work';
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';
@@ -307,6 +308,11 @@ export const buildRunLifecycle = (
if (get().operations[event.operationId]?.metadata.terminalReconciled) return;
if (adapter.runScope === 'sub_agent') return;
+ // The run's gh / push commands are linked by the completion Work scan,
+ // which finishes before the run reports its end. Only a mounted list
+ // (Better Coding Experience PR chip / sidebar) refetches.
+ void workService.refreshTopicPullRequests(topicId).catch(() => {});
+
const serverOperationId = get().operations[event.operationId]?.metadata.serverOperationId;
const disposition = resolveTerminalDisposition(event);
if (disposition === 'failed' && event.notification) {
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
index 6d0a4012c75..842885a3682 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
@@ -11,6 +11,8 @@ import {
toWorkingDirGithubState,
} from '@/store/chat/utils/topicWorkingDirGit';
import { deviceSelectors, getDeviceStoreState } from '@/store/device';
+import { getUserStoreState } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
import { topicSelectors } from '../../../topic/selectors';
@@ -83,9 +85,15 @@ export const snapshotTopicWorkingDirGit = async (
// No branch ref to query (unprobed / detached HEAD) → leave the prior snapshot.
if (!branch || detached) return;
- const prData = await gitService.getLinkedPullRequest({ branch, deviceId, path });
+ // Better Coding Experience links PRs only through the agent's own commands
+ // (server Work rows), so the send records the branch and its remote ref but
+ // no longer asks `gh` which PR the branch has.
+ const betterCoding = labPreferSelectors.enableBetterCodingExperience(getUserStoreState());
+ const prData = betterCoding
+ ? undefined
+ : await gitService.getLinkedPullRequest({ branch, deviceId, path });
const github = toWorkingDirGithubState(prData);
- if (!github) return;
+ if (!github && !betterCoding) return;
const nextConfig = mergeWorkingDirGithubState({
branch,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts
index 833fc4736f6..91a03f9c158 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts
@@ -19,6 +19,7 @@ vi.mock('@/services/work', async (importOriginal) => {
...actual,
workService: {
refreshConversationViews: vi.fn().mockResolvedValue(undefined),
+ refreshTopicPullRequests: vi.fn().mockResolvedValue(undefined),
},
};
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
index 3dc6a649323..696439dd002 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
@@ -18,6 +18,7 @@ vi.mock('@/services/work', async (importOriginal) => {
...actual,
workService: {
refreshConversationViews: vi.fn().mockResolvedValue(undefined),
+ refreshTopicPullRequests: vi.fn().mockResolvedValue(undefined),
},
};
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts
index 0831f84bba4..edcbc528e5b 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts
@@ -19,6 +19,7 @@ vi.mock('@/services/work', async (importOriginal) => {
...actual,
workService: {
refreshConversationViews: vi.fn().mockResolvedValue(undefined),
+ refreshTopicPullRequests: vi.fn().mockResolvedValue(undefined),
},
};
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts
index 2a5e3cb19fa..f73260dcfc9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts
@@ -18,6 +18,7 @@ vi.mock('@/services/work', async (importOriginal) => {
...actual,
workService: {
refreshConversationViews: vi.fn().mockResolvedValue(undefined),
+ refreshTopicPullRequests: vi.fn().mockResolvedValue(undefined),
},
};
});
diff --git a/src/store/chat/slices/topic/topicLinkedPullRequest.ts b/src/store/chat/slices/topic/topicLinkedPullRequest.ts
index 3925fd07e62..712ef177ba0 100644
--- a/src/store/chat/slices/topic/topicLinkedPullRequest.ts
+++ b/src/store/chat/slices/topic/topicLinkedPullRequest.ts
@@ -3,6 +3,8 @@ import { useEffect, useRef } from 'react';
import type { GitLinkedPRSummary } from '@/services/git';
import { gitLinkedPRKey } from '@/store/device/gitReview/projection';
import { useGitReviewStore } from '@/store/device/gitReview/store';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
export interface TopicLinkedPullRequestRefreshParams {
branch: string;
@@ -30,14 +32,18 @@ export const useTopicLinkedPullRequestSync = (
pr?: GitLinkedPRSummary,
) => Promise<void>,
) => {
- const replicaParams = params
- ? {
- branch: params.branch,
- deviceId: params.deviceId,
- path: params.path,
- pullRequestNumber: params.pullRequestNumber,
- }
- : null;
+ // Better Coding Experience reads a topic's PRs from its Work rows: the
+ // branch-guessed snapshot is neither refreshed nor written back.
+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);
+ const replicaParams =
+ params && !betterCoding
+ ? {
+ branch: params.branch,
+ deviceId: params.deviceId,
+ path: params.path,
+ pullRequestNumber: params.pullRequestNumber,
+ }
+ : null;
const key = replicaParams ? gitLinkedPRKey(replicaParams) : undefined;
const sync = useGitReviewStore.getState().slices.linkedPR.useSync(replicaParams, {
diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.ts
index 519a5560303..6ec8e0461ae 100644
--- a/src/store/chat/utils/topicWorkingDirGit.ts
+++ b/src/store/chat/utils/topicWorkingDirGit.ts
@@ -91,7 +91,12 @@ export const mergeWorkingDirGithubState = ({
}: {
branch: string;
currentConfig?: WorkingDirConfig;
- github: WorkingDirGithubState;
+ /**
+ * The linked-PR snapshot to record. Omitted under Better Coding Experience,
+ * which no longer guesses a PR from the branch: the one already recorded is
+ * kept while the branch stays, and dropped once it moves.
+ */
+ github?: WorkingDirGithubState;
path: string;
upstream?: DeviceGitUpstreamRef;
}): WorkingDirConfig => {
@@ -100,9 +105,10 @@ export const mergeWorkingDirGithubState = ({
const git: NonNullable<WorkingDirConfig['git']> = {
...currentConfig?.git,
branch,
- github,
isWorktree,
};
+ if (github) git.github = github;
+ else if (currentConfig?.git?.branch !== branch) delete git.github;
delete git.detached;
if (isWorktree) git.activeWorktree = path;
diff --git a/src/store/device/deviceReplicaFirstPaint.test.ts b/src/store/device/deviceReplicaFirstPaint.test.ts
index 8f6d6b01c43..32a4a151cd4 100644
--- a/src/store/device/deviceReplicaFirstPaint.test.ts
+++ b/src/store/device/deviceReplicaFirstPaint.test.ts
@@ -20,6 +20,7 @@ import { setScopedMutate } from '@/libs/swr/mutate';
import { deviceService } from '@/services/device';
import { gitService } from '@/services/git';
import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
import { useFetchGitLinkedPR, useGitRemoteBranches } from './gitHooks';
import { useFetchDeviceListeningPorts, useFetchDeviceTunnels } from './tunnelHooks';
@@ -262,4 +263,35 @@ describe('device replicas paint from storage first', () => {
expect(update.mock.calls[0][1]).toMatchObject({ pullRequest: { number: 7 } });
expect(gitService.getLinkedPullRequest).toHaveBeenCalledTimes(1);
});
+
+ it('neither refreshes nor writes back the branch-guessed PR under Better Coding Experience', async () => {
+ const preference = useUserStore.getState().preference;
+ useUserStore.setState({
+ preference: { ...preference, lab: { ...preference.lab, enableBetterCodingExperience: true } },
+ });
+ const metadata = {
+ workingDirectory: CWD,
+ workingDirectoryConfig: { git: { branch: 'feat/x' }, path: CWD, repoType: 'github' },
+ } as any;
+ const update = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ internal_updateTopicLinkedPullRequest: update,
+ } as any);
+
+ try {
+ renderHook(
+ () => useChatStore.getState().useFetchTopicLinkedPullRequest('topic-1', metadata),
+ {
+ wrapper,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ expect(gitService.getLinkedPullRequest).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ } finally {
+ useUserStore.setState({ preference });
+ }
+ });
});
diff --git a/src/store/tool/slices/builtin/executors/__tests__/pushedPullRequests.test.ts b/src/store/tool/slices/builtin/executors/__tests__/pushedPullRequests.test.ts
new file mode 100644
index 00000000000..0ac15aa22f9
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/pushedPullRequests.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { linkPushedPullRequests } from '../pushedPullRequests';
+
+const mocks = vi.hoisted(() => ({
+ getLinkedPullRequest: vi.fn(),
+ linkPushedPullRequests: vi.fn(),
+ refreshTopicPullRequests: vi.fn(),
+}));
+
+vi.mock('@/services/git', () => ({
+ gitService: { getLinkedPullRequest: mocks.getLinkedPullRequest },
+}));
+vi.mock('@/services/work', () => ({
+ workService: {
+ linkPushedPullRequests: mocks.linkPushedPullRequests,
+ refreshTopicPullRequests: mocks.refreshTopicPullRequests,
+ },
+}));
+
+const PARAMS = { branch: 'local', path: '/repo', toolCallId: 'call-1', topicId: 't1' };
+
+const lookup = (state = 'OPEN') => ({
+ pullRequest: {
+ isDraft: false,
+ number: 12,
+ state,
+ title: 'Feat',
+ url: 'https://github.com/lobehub/lobehub/pull/12',
+ },
+ pullRequestStatus: 'ok',
+ upstream: { branch: 'feat/x', remote: 'origin' },
+});
+
+describe('linkPushedPullRequests', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it("offers the device's open PR for the remote branch and refreshes the list", async () => {
+ mocks.getLinkedPullRequest.mockResolvedValue(lookup());
+ mocks.linkPushedPullRequests.mockResolvedValue({
+ linked: ['lobehub/lobehub#12'],
+ status: 'linked',
+ });
+
+ expect(await linkPushedPullRequests(PARAMS)).toEqual(['lobehub/lobehub#12']);
+ expect(mocks.getLinkedPullRequest).toHaveBeenCalledWith({
+ branch: 'local',
+ deviceId: undefined,
+ path: '/repo',
+ });
+ expect(mocks.linkPushedPullRequests).toHaveBeenCalledWith({
+ pullRequests: [
+ {
+ headRefName: 'feat/x',
+ isDraft: false,
+ number: 12,
+ state: 'OPEN',
+ title: 'Feat',
+ url: 'https://github.com/lobehub/lobehub/pull/12',
+ },
+ ],
+ toolCallId: 'call-1',
+ topicId: 't1',
+ });
+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledWith('t1');
+ });
+
+ it('never offers a merged or closed PR that shares the branch', async () => {
+ mocks.getLinkedPullRequest.mockResolvedValue(lookup('MERGED'));
+ mocks.linkPushedPullRequests.mockResolvedValue({ linked: [], status: 'linked' });
+
+ await linkPushedPullRequests(PARAMS);
+
+ expect(mocks.linkPushedPullRequests.mock.calls[0][0].pullRequests).toEqual([]);
+ expect(mocks.refreshTopicPullRequests).not.toHaveBeenCalled();
+ });
+
+ it('still asks the server (GitHub App) when the device cannot answer', async () => {
+ mocks.getLinkedPullRequest.mockResolvedValue({
+ pullRequest: null,
+ pullRequestStatus: 'gh-missing',
+ });
+ mocks.linkPushedPullRequests.mockResolvedValue({ linked: ['a/b#1'], status: 'linked' });
+
+ expect(await linkPushedPullRequests(PARAMS)).toEqual(['a/b#1']);
+ expect(mocks.linkPushedPullRequests.mock.calls[0][0].pullRequests).toEqual([]);
+ });
+
+ it('retries while the push is not persisted yet, then gives up', async () => {
+ mocks.getLinkedPullRequest.mockResolvedValue(lookup());
+ mocks.linkPushedPullRequests.mockResolvedValue({ status: 'pending' });
+
+ const done = linkPushedPullRequests(PARAMS);
+ await vi.runAllTimersAsync();
+
+ expect(await done).toEqual([]);
+ expect(mocks.linkPushedPullRequests).toHaveBeenCalledTimes(4);
+ });
+
+ it('stops once the server skips the call', async () => {
+ mocks.getLinkedPullRequest.mockResolvedValue(lookup());
+ mocks.linkPushedPullRequests.mockResolvedValue({ status: 'skipped' });
+
+ expect(await linkPushedPullRequests(PARAMS)).toEqual([]);
+ expect(mocks.linkPushedPullRequests).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows failures', async () => {
+ mocks.getLinkedPullRequest.mockRejectedValue(new Error('offline'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ expect(await linkPushedPullRequests(PARAMS)).toEqual([]);
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts
new file mode 100644
index 00000000000..6a32982d073
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { recordGitCommandEffects } from '../worktreeDetection';
+
+const chatMocks = vi.hoisted(() => ({
+ topics: {} as Record<string, { metadata?: Record<string, any> }>,
+ updateTopicMetadata: vi.fn(),
+}));
+const labMocks = vi.hoisted(() => ({ betterCoding: true }));
+const linkMocks = vi.hoisted(() => ({ linkPushedPullRequests: vi.fn(async () => []) }));
+const gsMocks = vi.hoisted(() => ({ revalidateGitStatus: vi.fn() }));
+
+vi.mock('@/store/device/gitStatus/store', () => ({ getGitStatusStoreState: () => gsMocks }));
+vi.mock('@/store/chat/store', () => ({ getChatStoreState: () => chatMocks }));
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (state: typeof chatMocks) => state.topics[id],
+ },
+}));
+vi.mock('@/services/git', () => ({ gitService: { listGitWorktrees: vi.fn() } }));
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'device-1' } }),
+}));
+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableBetterCodingExperience: () => labMocks.betterCoding },
+}));
+vi.mock('../pushedPullRequests', () => linkMocks);
+
+const topic = (git: Record<string, unknown> = { branch: 'feat/x' }) => ({
+ metadata: { workingDirectoryConfig: { git, path: '/repo', repoType: 'github' } },
+});
+
+const PUSH = {
+ command: 'git push',
+ resultContent: [
+ 'To github.com:lobehub/lobehub.git',
+ ' 031bf96..f6b1c2a feat/x -> feat/x',
+ ].join('\n'),
+};
+
+describe('recordGitCommandEffects — Better Coding Experience', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ labMocks.betterCoding = true;
+ chatMocks.topics = { t1: topic() };
+ });
+
+ it('records the push of a push-and-create chain but leaves the PR to the server', async () => {
+ await recordGitCommandEffects({
+ command: 'git push -u origin HEAD && gh pr create --title "Fix"',
+ resultContent: [
+ 'To github.com:lobehub/lobehub.git',
+ ' * [new branch] HEAD -> feat/x',
+ 'https://github.com/lobehub/lobehub/pull/456',
+ ].join('\n'),
+ toolCallId: 'call-1',
+ topicId: 't1',
+ });
+
+ const git = chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git;
+ expect(git.upstream).toEqual({ branch: 'feat/x', remote: 'origin' });
+ expect(git).not.toHaveProperty('github');
+ });
+
+ it('still records the upstream of a push, then links its PR through the server', async () => {
+ await recordGitCommandEffects({ ...PUSH, toolCallId: 'call-push', topicId: 't1' });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: {
+ git: { branch: 'feat/x', upstream: { branch: 'feat/x', remote: 'origin' } },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ expect(linkMocks.linkPushedPullRequests).toHaveBeenCalledWith({
+ branch: 'feat/x',
+ deviceId: undefined,
+ path: '/repo',
+ toolCallId: 'call-push',
+ topicId: 't1',
+ });
+ });
+
+ it('looks up on the bound remote device, in the topic worktree', async () => {
+ chatMocks.topics = {
+ t1: {
+ metadata: {
+ boundDeviceId: 'device-remote',
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/repo-wt', branch: 'feat/x', isWorktree: true },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ },
+ };
+
+ await recordGitCommandEffects({ ...PUSH, toolCallId: 'call-push', topicId: 't1' });
+
+ expect(linkMocks.linkPushedPullRequests).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-remote', path: '/repo-wt' }),
+ );
+ });
+
+ it('does not link without the call id, or with the lab off', async () => {
+ await recordGitCommandEffects({ ...PUSH, topicId: 't1' });
+ labMocks.betterCoding = false;
+ await recordGitCommandEffects({ ...PUSH, toolCallId: 'call-push', topicId: 't1' });
+
+ expect(linkMocks.linkPushedPullRequests).not.toHaveBeenCalled();
+ });
+
+ it('keeps binding gh pr create while the lab is off', async () => {
+ labMocks.betterCoding = false;
+
+ await recordGitCommandEffects({
+ command: 'gh pr create --title "Fix"',
+ resultContent: 'https://github.com/lobehub/lobehub/pull/456',
+ topicId: 't1',
+ });
+
+ expect(
+ chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git.github.pullRequest
+ .number,
+ ).toBe(456);
+ });
+
+ it('links a push whose result repeats the ref table under Stdout and Stderr', async () => {
+ const table = ['To github.com:lobehub/lobehub.git', ' 031bf96..f6b1c2a feat/x -> feat/x'];
+ await recordGitCommandEffects({
+ command: 'git push',
+ resultContent: ['Stdout:', ...table, 'Stderr:', ...table].join('\n'),
+ toolCallId: 'call-push',
+ topicId: 't1',
+ });
+
+ expect(linkMocks.linkPushedPullRequests).toHaveBeenCalledWith(
+ expect.objectContaining({ branch: 'feat/x', toolCallId: 'call-push' }),
+ );
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.ts
index 90d140e8c77..b622e8e5e7a 100644
--- a/src/store/tool/slices/builtin/executors/heteroCli.ts
+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts
@@ -72,6 +72,7 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
apiName,
params,
result,
+ toolCallId,
topicId,
}: ToolAfterCallContext): Promise<void> => {
// Constrain to a SUCCESSFUL call bound to a run topic. A refused `ExitWorktree`
@@ -93,7 +94,12 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
const command = readShellCommand(params);
if (command === undefined) return;
- await recordGitCommandEffects({ command, resultContent: result.content, topicId });
+ await recordGitCommandEffects({
+ command,
+ resultContent: result.content,
+ toolCallId,
+ topicId,
+ });
};
}
diff --git a/src/store/tool/slices/builtin/executors/localSystem.ts b/src/store/tool/slices/builtin/executors/localSystem.ts
index cf16b03965b..89854e66f5a 100644
--- a/src/store/tool/slices/builtin/executors/localSystem.ts
+++ b/src/store/tool/slices/builtin/executors/localSystem.ts
@@ -58,6 +58,7 @@ class LocalSystemExecutorWithGitEffects {
apiName,
params,
result,
+ toolCallId,
topicId,
}: ToolAfterCallContext): Promise<void> => {
// Constrain to a `runCommand` bound to a run topic whose command is KNOWN to
@@ -71,7 +72,12 @@ class LocalSystemExecutorWithGitEffects {
const command = readShellCommand(params);
if (command === undefined) return;
- await recordGitCommandEffects({ command, resultContent: result.content, topicId });
+ await recordGitCommandEffects({
+ command,
+ resultContent: result.content,
+ toolCallId,
+ topicId,
+ });
};
}
diff --git a/src/store/tool/slices/builtin/executors/pushedPullRequests.ts b/src/store/tool/slices/builtin/executors/pushedPullRequests.ts
new file mode 100644
index 00000000000..0e59b704043
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/pushedPullRequests.ts
@@ -0,0 +1,69 @@
+import { gitService } from '@/services/git';
+import { workService } from '@/services/work';
+
+/** Waits before re-asking while the push's tool row is still being persisted. */
+export const PUSH_LINK_RETRY_DELAYS = [1500, 4000, 10_000];
+
+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * After an agent's `git push` (Better Coding Experience), link the pull
+ * request the pushed branch already has to the topic.
+ *
+ * The execution device answers which PR heads the branch (`gh pr list --head`
+ * on its remote ref) — the only source when no GitHub App tracks the repo.
+ * The SERVER decides: it re-reads the push from the persisted tool message,
+ * prefers the GitHub App's rows, and accepts the device's answer only for the
+ * repository and branch git itself reported. Only an open PR is offered: a
+ * merged or closed one that happened to share the branch name is not the one
+ * this push is for.
+ *
+ * Best-effort; never throws. Resolves to the linked identifiers.
+ */
+export const linkPushedPullRequests = async (params: {
+ branch: string;
+ deviceId?: string;
+ path: string;
+ toolCallId: string;
+ topicId: string;
+}): Promise<string[]> => {
+ try {
+ const lookup = await gitService.getLinkedPullRequest({
+ branch: params.branch,
+ deviceId: params.deviceId,
+ path: params.path,
+ });
+ const pr = lookup?.pullRequestStatus === 'ok' ? lookup.pullRequest : null;
+ const headRefName = lookup?.upstream?.branch;
+ const pullRequests =
+ pr && headRefName && pr.state.toLowerCase() === 'open'
+ ? [
+ {
+ headRefName,
+ isDraft: pr.isDraft,
+ number: pr.number,
+ state: pr.state,
+ title: pr.title,
+ url: pr.url,
+ },
+ ]
+ : [];
+
+ for (let attempt = 0; ; attempt++) {
+ const result = await workService.linkPushedPullRequests({
+ pullRequests,
+ toolCallId: params.toolCallId,
+ topicId: params.topicId,
+ });
+ if (result.status === 'linked') {
+ if (result.linked.length > 0) await workService.refreshTopicPullRequests(params.topicId);
+ return result.linked;
+ }
+ if (result.status === 'skipped' || attempt >= PUSH_LINK_RETRY_DELAYS.length) return [];
+ await wait(PUSH_LINK_RETRY_DELAYS[attempt]);
+ }
+ } catch (error) {
+ console.error('[linkPushedPullRequests] failed:', error);
+ return [];
+ }
+};
diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
index bcaeca56b53..9e9af6772c7 100644
--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts
+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
@@ -1,6 +1,6 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceGitUpstreamRef } from '@lobechat/types';
-import { getWorkingDirSourcePath } from '@lobechat/types';
+import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { gitService } from '@/services/git';
@@ -8,7 +8,10 @@ import { topicSelectors } from '@/store/chat/selectors';
import { getChatStoreState } from '@/store/chat/store';
import { getGitStatusStoreState } from '@/store/device/gitStatus/store';
import { getElectronStoreState } from '@/store/electron';
+import { getUserStoreState } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+import { linkPushedPullRequests } from './pushedPullRequests';
import {
applyBranchToConfig,
applyDetachedToConfig,
@@ -476,7 +479,11 @@ const parsePushRefMappings = (content?: string): PushRefMapping[] => {
if (local === '(none)' || local.startsWith('refs/tags/') || remote.startsWith('refs/tags/'))
continue;
- mappings.push({ local, remote: remote.replace(/^refs\/heads\//, '') });
+ const mapping = { local, remote: remote.replace(/^refs\/heads\//, '') };
+ // git writes the table to stderr; a result that carries both streams (or
+ // echoes them) states the same mapping twice — one ref, not an ambiguity.
+ if (!mappings.some((m) => m.local === mapping.local && m.remote === mapping.remote))
+ mappings.push(mapping);
}
return mappings;
};
@@ -919,10 +926,14 @@ export const recordWorktreeAdd = async (params: {
export const recordGitCommandEffects = async (params: {
command: string | string[];
resultContent?: string;
+ /** The shell call's id; lets the server re-read a push to link its PR. */
+ toolCallId?: string;
topicId: string;
}): Promise<void> => {
- const { command, resultContent, topicId } = params;
+ const { command, resultContent, toolCallId, topicId } = params;
const state = getChatStoreState();
+ // Better Coding Experience: PRs reach the topic only as server Work rows.
+ const betterCoding = labPreferSelectors.enableBetterCodingExperience(getUserStoreState());
const topic = topicSelectors.getTopicById(topicId)(state);
const currentConfig = topic?.metadata?.workingDirectoryConfig;
@@ -966,7 +977,7 @@ export const recordGitCommandEffects = async (params: {
nextConfig = applyPushToConfig(nextConfig, source, pushUpstream);
}
- const prCreate = parseGhPrCreate(command, resultContent);
+ const prCreate = betterCoding ? undefined : parseGhPrCreate(command, resultContent);
if (prCreate) {
nextConfig = applyPullRequestToConfig(nextConfig, source, prCreate);
}
@@ -987,6 +998,18 @@ export const recordGitCommandEffects = async (params: {
currentDeviceId && boundDeviceId === currentDeviceId ? 'local' : boundDeviceId;
const revalidateDeviceId = cacheDeviceId === 'local' ? undefined : cacheDeviceId;
await getGitStatusStoreState().revalidateGitStatus(revalidateDeviceId, source, ['branch']);
+
+ const branch = nextConfig?.git?.branch;
+ if (betterCoding && pushUpstream && toolCallId && branch) {
+ // Not awaited: the device lookup and the server's re-read may retry.
+ void linkPushedPullRequests({
+ branch,
+ deviceId: revalidateDeviceId,
+ path: getWorkingDirEffectivePath(nextConfig) ?? source,
+ toolCallId,
+ topicId,
+ });
+ }
}
};
diff --git a/src/store/work/action.ts b/src/store/work/action.ts
index 42a916edc23..ff044fb87a9 100644
--- a/src/store/work/action.ts
+++ b/src/store/work/action.ts
@@ -1,4 +1,4 @@
-import type { WorkListItem, WorkVersionItem } from '@lobechat/types';
+import type { TopicPullRequestItem, WorkListItem, WorkVersionItem } from '@lobechat/types';
import type { ReplicaSyncOptions } from 'local-replica/zustand';
import type { ReplicaSyncResult } from '@/libs/replica';
@@ -10,6 +10,7 @@ import { WorkPrivateAction } from './privateAction';
import {
type AgentWorksParams,
type ConversationWorksParams,
+ type TopicPullRequestsParams,
workspaceWorksKey,
type WorkspaceWorksParams,
type WorkVersionsParams,
@@ -84,6 +85,12 @@ export class WorkActionImpl {
options?: ReplicaSyncOptions<WorkListItem[], WorkListItem[]>,
): ReplicaSyncResult => this.#private.conversationWorks.useSync(params, options);
+ /** Pull requests linked to a topic (Better Coding Experience); `null` disables the read. */
+ useFetchTopicPullRequests = (
+ params: TopicPullRequestsParams | null,
+ options?: ReplicaSyncOptions<TopicPullRequestItem[], TopicPullRequestItem[]>,
+ ): ReplicaSyncResult => this.#private.topicPullRequests.useSync(params, options);
+
useFetchWorkVersions = (
params: WorkVersionsParams | null,
options?: ReplicaSyncOptions<WorkVersionItem[], WorkVersionItem[]>,
diff --git a/src/store/work/initialState.ts b/src/store/work/initialState.ts
index da8417af986..4c444831fbd 100644
--- a/src/store/work/initialState.ts
+++ b/src/store/work/initialState.ts
@@ -1,4 +1,9 @@
-import type { WorkListItem, WorkSummaryItem, WorkVersionItem } from '@lobechat/types';
+import type {
+ TopicPullRequestItem,
+ WorkListItem,
+ WorkSummaryItem,
+ WorkVersionItem,
+} from '@lobechat/types';
import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';
@@ -12,6 +17,9 @@ export interface WorkState {
/** Sidebar Work history by conversation (`conversationWorksKey`). */
conversationWorksMap: Record<string, WorkListItem[]>;
conversationWorksReplica: ReplicaState<WorkListItem[]>;
+ /** Pull requests linked to a topic, by topic id. */
+ topicPullRequestsMap: Record<string, TopicPullRequestItem[]>;
+ topicPullRequestsReplica: ReplicaState<TopicPullRequestItem[]>;
/** Workspace gallery pages by filter (`workspaceWorksKey`). */
workspaceWorksMap: Record<string, WorkspaceWorksData>;
workspaceWorksReplica: ReplicaState<WorkspaceWorksData>;
@@ -25,6 +33,8 @@ export const initialWorkState: WorkState = {
agentWorksReplica: createReplicaState(),
conversationWorksMap: {},
conversationWorksReplica: createReplicaState(),
+ topicPullRequestsMap: {},
+ topicPullRequestsReplica: createReplicaState(),
workVersionsMap: {},
workVersionsReplica: createReplicaState(),
workspaceWorksMap: {},
diff --git a/src/store/work/privateAction.ts b/src/store/work/privateAction.ts
index ce3308d5b40..cd61d4e4eff 100644
--- a/src/store/work/privateAction.ts
+++ b/src/store/work/privateAction.ts
@@ -1,4 +1,9 @@
-import type { WorkListItem, WorkSummaryItem, WorkVersionItem } from '@lobechat/types';
+import type {
+ TopicPullRequestItem,
+ WorkListItem,
+ WorkSummaryItem,
+ WorkVersionItem,
+} from '@lobechat/types';
import {
arrayEntity,
@@ -18,6 +23,7 @@ import {
agentWorksResource,
conversationWorksResource,
toPersistedVersions,
+ topicPullRequestsResource,
WORKSPACE_WORKS_PAGE_SIZE,
type WorkspaceWorksParams,
workspaceWorksResource,
@@ -33,6 +39,7 @@ const workId = (item: { id: string }) => item.id;
export class WorkPrivateAction {
readonly agentWorks;
readonly conversationWorks;
+ readonly topicPullRequests;
readonly versions;
readonly workspaceWorks;
/** One Work card everywhere it is listed: gallery, project dashboard, sidebar history. */
@@ -71,6 +78,14 @@ export class WorkPrivateAction {
stateKey: 'conversationWorksReplica',
view: recordLens<WorkState, WorkListItem[]>('conversationWorksMap'),
});
+ this.topicPullRequests = createReplicaSlice(topicPullRequestsResource, {
+ actionPrefix: n('topicPullRequests'),
+ fetcher: ({ topicId }) => workService.listTopicPullRequests(topicId),
+ get,
+ set,
+ stateKey: 'topicPullRequestsReplica',
+ view: recordLens<WorkState, TopicPullRequestItem[]>('topicPullRequestsMap'),
+ });
this.versions = createReplicaSlice(workVersionsResource, {
actionPrefix: n('versions'),
fetcher: ({ workId }) => workService.listVersions(workId),
diff --git a/src/store/work/projection.ts b/src/store/work/projection.ts
index 406c054e55c..4e92a456d5c 100644
--- a/src/store/work/projection.ts
+++ b/src/store/work/projection.ts
@@ -1,5 +1,6 @@
import type {
ListedWorkType,
+ TopicPullRequestItem,
WorkListItem,
WorkSkillProvider,
WorkSummaryItem,
@@ -105,6 +106,28 @@ export const conversationWorksResource = defineReplica<ConversationWorksParams,
version: 1,
});
+export interface TopicPullRequestsParams {
+ topicId: string;
+}
+
+/**
+ * The pull requests a topic's Work rows link (Better Coding Experience): the
+ * control bar's PR chip and the working sidebar's repository card. A reload
+ * paints the last list — with the last known states — before the network
+ * answers. Revalidated by `workService.refreshTopicPullRequests` (run end,
+ * conversation view refresh, a linked push).
+ */
+export const topicPullRequestsResource = defineReplica<
+ TopicPullRequestsParams,
+ TopicPullRequestItem[]
+>({
+ key: ({ topicId }) => topicId,
+ name: 'topicPullRequests',
+ persist: { maxEntries: 100 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
export interface WorkVersionsParams {
workId: string;
}
diff --git a/src/store/work/selectors.ts b/src/store/work/selectors.ts
index 885c1172129..62e6706f089 100644
--- a/src/store/work/selectors.ts
+++ b/src/store/work/selectors.ts
@@ -18,9 +18,13 @@ const conversationWorks = (params: ConversationWorksParams | null) => (s: WorkSt
const workVersions = (workId: string) => (s: WorkState) => s.workVersionsMap[workId];
+const topicPullRequests = (topicId: string | null | undefined) => (s: WorkState) =>
+ topicId ? s.topicPullRequestsMap[topicId] : undefined;
+
export const workSelectors = {
agentWorks,
conversationWorks,
+ topicPullRequests,
workspaceWorks,
workVersions,
};