🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(coding): say how each topic PR was linked; own-branch match, manual link and remove (#23248)
Bryan077e32942ef7
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.tsindex 7525925a80b..beb66bf0f83 100644--- a/apps/desktop/src/main/controllers/GitCtr.ts+++ b/apps/desktop/src/main/controllers/GitCtr.ts@@ -65,6 +65,7 @@ export default class GitController extends ControllerModule {branch: string;path: string;pullRequestNumber?: number;+ state?: 'all' | 'open';}): Promise<GitLinkedPullRequestResult> {const { getLinkedPullRequest: computeLinkedPullRequest } = await loadGit();return computeLinkedPullRequest(payload);diff --git a/apps/server/src/routers/lambda/__tests__/work.test.ts b/apps/server/src/routers/lambda/__tests__/work.test.tsindex 3a156f5629b..0c733ca23c3 100644--- a/apps/server/src/routers/lambda/__tests__/work.test.ts+++ b/apps/server/src/routers/lambda/__tests__/work.test.ts@@ -101,4 +101,21 @@ describe('workRouter — per-procedure write permission gates', () => {await expect(createCaller().listByConversation({})).resolves.toEqual([]);expect(mockListByConversation).toHaveBeenCalledTimes(1);});++ it('the topic PR link and dismiss endpoints gate on topic:update', async () => {+ await expect(+ createCaller().linkTopicPullRequest({+ source: 'manual',+ topicId: 't1',+ url: 'https://github.com/a/b/pull/1',+ }),+ ).rejects.toThrow('GATE:topic:update');+ await expect(+ createCaller().setTopicPullRequestDismissed({+ dismissed: true,+ identifier: 'a/b#1',+ topicId: 't1',+ }),+ ).rejects.toThrow('GATE:topic:update');+ });});diff --git a/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.tsnew file mode 100644index 00000000000..1a14c5d6f7b--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ assertCanUseTopicTargets: vi.fn(),+ linkTopicPullRequest: vi.fn(async () => true),+ setTopicPullRequestDismissed: vi.fn(async () => true),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));+// Let the RBAC gate through: this file is about the conversation access guard.+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: () => (opts: { next: () => unknown }) => opts.next(),+}));+vi.mock('../_helpers/conversationResourceGuard', () => ({+ assertCanUseTopicTargets: mocks.assertCanUseTopicTargets,+}));+const Model = vi.fn(function () {+ return {};+});+vi.mock('@/database/models/message', () => ({ MessageModel: Model }));+vi.mock('@/database/models/work', () => ({ WorkModel: Model }));+vi.mock('@/database/models/topic', () => ({ TopicModel: Model }));+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({+ ...(await importOriginal<any>()),+ isBetterCodingExperienceEnabled: vi.fn(async () => true),+ linkTopicPullRequest: mocks.linkTopicPullRequest,+ setTopicPullRequestDismissed: mocks.setTopicPullRequestDismissed,+}));++const { workRouter } = await import('../work');++const caller = () =>+ workRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' } as any);++describe('workRouter — topic PR links honour conversation access', () => {+ beforeEach(() => vi.clearAllMocks());++ it('refuses to link or remove a PR on a topic the caller cannot use', async () => {+ mocks.assertCanUseTopicTargets.mockRejectedValue(new Error('FORBIDDEN'));++ await expect(+ caller().linkTopicPullRequest({+ source: 'manual',+ topicId: 't1',+ url: 'https://github.com/a/b/pull/1',+ }),+ ).rejects.toThrow('FORBIDDEN');+ await expect(+ caller().setTopicPullRequestDismissed({+ dismissed: true,+ identifier: 'a/b#1',+ topicId: 't1',+ }),+ ).rejects.toThrow('FORBIDDEN');++ expect(mocks.assertCanUseTopicTargets).toHaveBeenCalledWith(+ { db: {}, userId: 'user-1', workspaceId: 'ws-1' },+ ['t1'],+ );+ expect(mocks.linkTopicPullRequest).not.toHaveBeenCalled();+ expect(mocks.setTopicPullRequestDismissed).not.toHaveBeenCalled();+ });++ it('writes once access is confirmed', async () => {+ mocks.assertCanUseTopicTargets.mockResolvedValue([]);++ expect(+ await caller().linkTopicPullRequest({+ source: 'manual',+ topicId: 't1',+ url: 'https://github.com/a/b/pull/1',+ }),+ ).toEqual({ identifier: 'a/b#1', linked: true });+ expect(+ await caller().setTopicPullRequestDismissed({+ dismissed: true,+ identifier: 'a/b#1',+ topicId: 't1',+ }),+ ).toEqual({ updated: true });+ });+});diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsindex 07ae0f4896b..4181c33432a 100644--- a/apps/server/src/routers/lambda/device/git.ts+++ b/apps/server/src/routers/lambda/device/git.ts@@ -74,6 +74,7 @@ export const gitRouter = router({deviceId: z.string(),path: z.string(),pullRequestNumber: z.number().optional(),+ state: z.enum(['all', 'open']).optional(),}),).query(async ({ ctx, input }) => {@@ -82,6 +83,7 @@ export const gitRouter = router({deviceId: input.deviceId,path: input.path,pullRequestNumber: input.pullRequestNumber,+ state: input.state,userId: ctx.userId,workspaceId: ctx.workspaceId,});diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex 8bf8246f585..c8a4f57537c 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -12,18 +12,32 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';import { WorkModel } from '@/database/models/work';+import type { LobeChatDatabase } from '@/database/type';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 {+ isBetterCodingExperienceEnabled,linkPushedPullRequests,+ linkTopicPullRequest,listTopicPullRequestsWithStatus,+ parsePullRequestUrl,registerShellWorksForLocalRun,resolveShellPullRequestLinking,+ setTopicPullRequestDismissed,} from '@/server/services/workRegistration';+import { assertCanUseTopicTargets } from './_helpers/conversationResourceGuard';++const topicGuardCtx = (ctx: {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}) => ({ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId });+const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;@@ -31,6 +45,7 @@ const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>return opts.next({ctx: {messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),workModel: new WorkModel(ctx.serverDB, ctx.userId, wsId),},});@@ -297,6 +312,7 @@ export const workRouter = router({listTopicPullRequestsWithStatus({db: ctx.serverDB,topicId: input.topicId,+ topicModel: ctx.topicModel,userId: ctx.userId,workModel: ctx.workModel,workspaceId: ctx.workspaceId,@@ -313,6 +329,7 @@ export const workRouter = router({.array(z.object({headRefName: z.string().min(1).max(255),+ headRepoFullName: z.string().max(255).optional(),isDraft: z.boolean().optional(),number: z.number().int().positive(),state: z.string().max(32).optional(),@@ -337,4 +354,67 @@ export const workRouter = router({workspaceId: ctx.workspaceId,}),),++ // Better Coding Experience: keep a PR on the topic itself — found on the+ // topic's own branch at run end (`branch`), or pasted by the person+ // (`manual`). A topic link only drives the topic's PR lists: unlike a Work+ // row it is never read by the SCM links, so a client-named PR cannot make a+ // merge accept a delivery or a CI failure wake the agent.+ linkTopicPullRequest: workProcedure+ .use(withScopedPermission('topic:update'))+ .input(+ z.object({+ headRefName: z.string().max(255).optional(),+ source: z.enum(['branch', 'manual']),+ title: z.string().max(1024).optional(),+ topicId: z.string().min(1),+ url: z.string().max(2048),+ /** Branch matches only: the PR's head lives in the repo the topic pushes to. */+ vouched: z.boolean().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ // Same gate as topic.updateTopicMetadata: `use` access to the conversation.+ await assertCanUseTopicTargets(topicGuardCtx(ctx), [input.topicId]);+ const parsed = parsePullRequestUrl(input.url);+ if (!parsed) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Not a GitHub pull request URL' });+ }+ if (!(await isBetterCodingExperienceEnabled(ctx.serverDB, ctx.userId))) {+ return { identifier: parsed.identifier, linked: false };+ }+ const linked = await linkTopicPullRequest(ctx.topicModel, input.topicId, {+ ...(input.headRefName ? { headRefName: input.headRefName } : {}),+ identifier: parsed.identifier,+ source: input.source,+ ...(input.title ? { title: input.title } : {}),+ url: parsed.url,+ // The person vouches for what they link by hand.+ vouched: input.source === 'manual' ? true : !!input.vouched,+ });+ return { identifier: parsed.identifier, linked };+ }),++ // Better Coding Experience: remove a PR from the topic's lists (or bring it+ // back). Its Work rows stay; only the topic's view of them changes.+ setTopicPullRequestDismissed: workProcedure+ .use(withScopedPermission('topic:update'))+ .input(+ z.object({+ dismissed: z.boolean(),+ identifier: z.string().regex(/^[\w.-]+\/[\w.-]+#\d+$/),+ topicId: z.string().min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertCanUseTopicTargets(topicGuardCtx(ctx), [input.topicId]);+ return {+ updated: await setTopicPullRequestDismissed(+ ctx.topicModel,+ input.topicId,+ input.identifier,+ input.dismissed,+ ),+ };+ }),});diff --git a/apps/server/src/services/deviceGateway/gitRead.ts b/apps/server/src/services/deviceGateway/gitRead.tsindex 705414107a6..0aabeaa0f94 100644--- a/apps/server/src/services/deviceGateway/gitRead.ts+++ b/apps/server/src/services/deviceGateway/gitRead.ts@@ -41,6 +41,7 @@ export function gitLinkedPullRequest(deviceId: string;path: string;pullRequestNumber?: number;+ state?: 'all' | 'open';userId: string;workspaceId?: string;},@@ -53,6 +54,8 @@ export function gitLinkedPullRequest(branch: params.branch,path: params.path,pullRequestNumber: params.pullRequestNumber,+ // Only when asked: a device that predates `state` keeps listing all.+ ...(params.state ? { state: params.state } : {}),},);}diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.tsindex 8caa90e56a1..7218520a780 100644--- a/apps/server/src/services/workRegistration/index.ts+++ b/apps/server/src/services/workRegistration/index.ts@@ -33,6 +33,11 @@ export {} from './registerWorksForOperation';export { resolveRunWorkAccessScope, type ShareVisitorWorkIdentity } from './shareWorkScope';export { stateHasEntityFileEdits } from './stateHasEntityFileEdits';+export {+ linkTopicPullRequest,+ parsePullRequestUrl,+ setTopicPullRequestDismissed,+} from './topicPullRequestLinks';export {type DeviceReportedPullRequest,linkPushedPullRequests,diff --git a/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts b/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.tsindex 15d734a71a7..9a7a0ed36b3 100644--- a/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts+++ b/apps/server/src/services/workRegistration/shellWorkRegistration.pullRequests.test.ts@@ -81,7 +81,7 @@ describe('registerShellWorks · pull request linking', () => {expect.objectContaining({changeType: 'updated',messageId: 'm1',- metadata: { headBranch: 'feat/x' },+ metadata: { headBranch: 'feat/x', pullRequestLink: 'push' },patchFields: ['identifier', 'title', 'url'],resourceId: 'lobehub/lobehub#12',resourceType: 'github_pull_request',diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.tsindex cbaa9556b8d..464279eae20 100644--- a/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts+++ b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts@@ -36,7 +36,10 @@ export const githubPushShellWorkScanner: ShellWorkScanner = {cumulativeUsage: input.cumulativeUsage,identifier,messageId: input.messageId,- ...(pullRequest.headRef ? { metadata: { headBranch: pullRequest.headRef } } : {}),+ metadata: {+ ...(pullRequest.headRef ? { headBranch: pullRequest.headRef } : {}),+ pullRequestLink: 'push',+ },patchFields: pullRequest.title ? ['identifier', 'title', 'url'] : ['identifier', 'url'],resourceId: identifier,resourceType: 'github_pull_request',diff --git a/apps/server/src/services/workRegistration/topicPullRequestLinks.test.ts b/apps/server/src/services/workRegistration/topicPullRequestLinks.test.tsnew file mode 100644index 00000000000..7b1ded17df8--- /dev/null+++ b/apps/server/src/services/workRegistration/topicPullRequestLinks.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it, vi } from 'vitest';++import {+ linkTopicPullRequest,+ parsePullRequestUrl,+ setTopicPullRequestDismissed,+} from './topicPullRequestLinks';++/** An in-memory topic row whose metadata writes honour `onlyIf`. */+const createTopicModel = (pullRequests?: Record<string, unknown>, interleave?: () => void) => {+ const row = { metadata: pullRequests ? { pullRequests } : ({} as Record<string, any>) };+ return {+ findById: vi.fn(async () => structuredClone(row)),+ row,+ updateMetadata: vi.fn(async (_id: string, patch: any, options: any) => {+ interleave?.();+ if (options?.onlyIf && !options.onlyIf(row.metadata)) return [];+ row.metadata = { ...row.metadata, ...patch };+ return [row];+ }),+ };+};++const link = (n: number, source: 'branch' | 'manual' = 'manual') => ({+ identifier: `a/b#${n}`,+ source,+ url: `https://github.com/a/b/pull/${n}`,+ vouched: source === 'manual',+});++describe('parsePullRequestUrl', () => {+ it('reads a github.com pull request URL into its identity', () => {+ expect(parsePullRequestUrl(' https://github.com/LobeHub/lobehub/pull/12/files?x=1 ')).toEqual({+ identifier: 'LobeHub/lobehub#12',+ number: 12,+ repoFullName: 'LobeHub/lobehub',+ url: 'https://github.com/LobeHub/lobehub/pull/12',+ });+ expect(parsePullRequestUrl('https://github.com/a/b/issues/1')).toBeNull();+ expect(parsePullRequestUrl('http://evil.com/a/b/pull/1')).toBeNull();+ });+});++describe('linkTopicPullRequest', () => {+ it('adds a link and brings a removed PR back', async () => {+ const topicModel = createTopicModel({ dismissed: ['a/b#1'] });++ expect(await linkTopicPullRequest(topicModel as any, 't1', link(1))).toBe(true);++ expect(topicModel.row.metadata.pullRequests.dismissed).toBeUndefined();+ expect(topicModel.row.metadata.pullRequests.links).toEqual([+ expect.objectContaining({ identifier: 'a/b#1', source: 'manual', vouched: true }),+ ]);+ });++ it('never lets a branch match downgrade a manual link or undo a removal', async () => {+ const manual = createTopicModel({ links: [{ ...link(1), linkedAt: '2026-11-01T00:00:00Z' }] });+ await linkTopicPullRequest(manual as any, 't1', link(1, 'branch'));+ expect(manual.row.metadata.pullRequests.links[0].source).toBe('manual');+ expect(manual.updateMetadata).not.toHaveBeenCalled();++ const removed = createTopicModel({ dismissed: ['A/B#2'] });+ await linkTopicPullRequest(removed as any, 't1', link(2, 'branch'));+ expect(removed.updateMetadata).not.toHaveBeenCalled();+ });++ it('retries against a write that landed in between', async () => {+ let raced = false;+ const topicModel = createTopicModel(undefined, () => {+ if (raced) return;+ raced = true;+ topicModel.row.metadata = {+ pullRequests: { links: [{ ...link(9), linkedAt: '2026-11-01T00:00:00Z' }] },+ };+ });++ expect(await linkTopicPullRequest(topicModel as any, 't1', link(1))).toBe(true);+ expect(topicModel.row.metadata.pullRequests.links.map((l: any) => l.identifier)).toEqual([+ 'a/b#9',+ 'a/b#1',+ ]);+ });++ it('writes nothing for a topic the caller cannot read', async () => {+ const topicModel = { findById: vi.fn(async () => undefined), updateMetadata: vi.fn() };+ expect(await linkTopicPullRequest(topicModel as any, 't1', link(1))).toBe(false);+ expect(topicModel.updateMetadata).not.toHaveBeenCalled();+ });+});++describe('setTopicPullRequestDismissed', () => {+ it('hides and shows a PR without touching its links', async () => {+ const topicModel = createTopicModel({ links: [{ ...link(1), linkedAt: 'x' }] });++ await setTopicPullRequestDismissed(topicModel as any, 't1', 'a/b#1', true);+ expect(topicModel.row.metadata.pullRequests).toMatchObject({ dismissed: ['a/b#1'] });++ await setTopicPullRequestDismissed(topicModel as any, 't1', 'A/B#1', false);+ expect(topicModel.row.metadata.pullRequests.dismissed).toBeUndefined();+ expect(topicModel.row.metadata.pullRequests.links).toHaveLength(1);+ });+});diff --git a/apps/server/src/services/workRegistration/topicPullRequestLinks.ts b/apps/server/src/services/workRegistration/topicPullRequestLinks.tsnew file mode 100644index 00000000000..4db0451f127--- /dev/null+++ b/apps/server/src/services/workRegistration/topicPullRequestLinks.ts@@ -0,0 +1,109 @@+import type { TopicPullRequestLinkMeta, TopicPullRequestsMeta } from '@lobechat/types';+import isEqual from 'fast-deep-equal';++import type { TopicModel } from '@/database/models/topic';++/** Bounds what one topic can carry; the oldest links fall off first. */+const MAX_TOPIC_LINKS = 50;+const MAX_DISMISSED = 100;+/** Concurrent writers each retry against the row they lost to. */+const MAX_WRITE_ATTEMPTS = 3;++/** A github.com PR page, also one of its tabs (`/files`) or with a query / anchor. */+const PULL_URL_RE = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:[/?#]\S*)?$/i;++/** `owner/repo#number` and the canonical URL of a github.com pull request URL. */+export const parsePullRequestUrl = (+ url: string,+): { identifier: string; number: number; repoFullName: string; url: string } | null => {+ const match = PULL_URL_RE.exec(url.trim());+ if (!match) return null;+ const repoFullName = `${match[1]}/${match[2]}`;+ const number = Number(match[3]);+ return {+ identifier: `${repoFullName}#${number}`,+ number,+ repoFullName,+ url: `https://github.com/${repoFullName}/pull/${number}`,+ };+};++const sameIdentifier = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();++/** Empty lists are dropped so "nothing" has one shape. */+const tidy = (meta: TopicPullRequestsMeta): TopicPullRequestsMeta => ({+ ...(meta.dismissed?.length ? { dismissed: meta.dismissed } : {}),+ ...(meta.links?.length ? { links: meta.links } : {}),+});++/**+ * Rewrite a topic's `metadata.pullRequests` atomically: `update` sees the+ * value the write will replace, and the write only lands if nobody changed it+ * since (else it retries on the newer value). False when the topic is not+ * the caller's, or the writers kept colliding.+ */+const updateTopicPullRequests = async (+ topicModel: TopicModel,+ topicId: string,+ update: (current: TopicPullRequestsMeta) => TopicPullRequestsMeta,+): Promise<boolean> => {+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {+ const topic = await topicModel.findById(topicId);+ if (!topic) return false;+ const current = topic.metadata?.pullRequests;+ const next = tidy(update(tidy(current ?? {})));+ if (isEqual(tidy(current ?? {}), next)) return true;++ const rows = await topicModel.updateMetadata(+ topicId,+ { pullRequests: next },+ { onlyIf: (metadata) => isEqual(metadata?.pullRequests, current) },+ );+ if (rows.length > 0) return true;+ }+ return false;+};++/**+ * Keep a PR on the topic itself: one found on the topic's own branch, or one+ * the person linked by URL. Linking a PR also brings it back if it had been+ * removed. A by-hand link outranks a branch match of the same PR.+ */+export const linkTopicPullRequest = (+ topicModel: TopicModel,+ topicId: string,+ link: Omit<TopicPullRequestLinkMeta, 'linkedAt'>,+): Promise<boolean> =>+ updateTopicPullRequests(topicModel, topicId, (current) => {+ const links = current.links ?? [];+ const existing = links.find((item) => sameIdentifier(item.identifier, link.identifier));+ // A branch match never downgrades a by-hand link, nor re-links one removed by hand.+ if (link.source === 'branch') {+ if (existing?.source === 'manual') return current;+ if (current.dismissed?.some((id) => sameIdentifier(id, link.identifier))) return current;+ }+ const next: TopicPullRequestLinkMeta = {+ ...link,+ linkedAt: existing?.linkedAt ?? new Date().toISOString(),+ };+ return {+ ...current,+ dismissed: current.dismissed?.filter((id) => !sameIdentifier(id, link.identifier)),+ links: [...links.filter((item) => item !== existing), next].slice(-MAX_TOPIC_LINKS),+ };+ });++/** Hide a linked PR from the topic's lists (or show it again). The Work rows stay. */+export const setTopicPullRequestDismissed = (+ topicModel: TopicModel,+ topicId: string,+ identifier: string,+ dismissed: boolean,+): Promise<boolean> =>+ updateTopicPullRequests(topicModel, topicId, (current) => {+ const rest = (current.dismissed ?? []).filter((id) => !sameIdentifier(id, identifier));+ return {+ ...current,+ dismissed: dismissed ? [...rest, identifier].slice(-MAX_DISMISSED) : rest,+ };+ });diff --git a/apps/server/src/services/workRegistration/topicPullRequests.test.ts b/apps/server/src/services/workRegistration/topicPullRequests.test.tsindex 92fd0513eb3..7ec91d0a946 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.test.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.test.ts@@ -19,12 +19,15 @@ vi.mock('@/database/models/scm', () => ({}));const db = {} as any;+const topicModelWith = (pullRequests?: unknown) =>+ ({ findById: vi.fn(async () => ({ metadata: pullRequests ? { pullRequests } : {} })) }) as any;const workItem = (number: number, repoFullName = 'lobehub/lobehub') => ({identifier: `${repoFullName}#${number}`,linkedAt: new Date('2026-11-17T00:00:00Z'),number,repoFullName,+ source: 'created',status: 'open',title: `PR ${number}`,url: `https://github.com/${repoFullName}/pull/${number}`,@@ -56,6 +59,7 @@ describe('listTopicPullRequestsWithStatus', () => {const items = await listTopicPullRequestsWithStatus({db,topicId: 't1',+ topicModel: topicModelWith(),userId: 'u1',workModel,workspaceId: 'ws1',@@ -75,13 +79,62 @@ describe('listTopicPullRequestsWithStatus', () => {updatedAt,});expect(items[1].scm).toBeNull();+ expect(items.every((item) => item.vouched)).toBe(true);+ });++ it('adds the topic links, hides removed PRs, and keeps the latest link first', async () => {+ listByIdentities.mockResolvedValue([]);+ const workModel = {+ listTopicPullRequests: vi.fn(async () => [workItem(1), workItem(2)]),+ } as any;+ const topicModel = topicModelWith({+ dismissed: ['LobeHub/lobehub#2'],+ links: [+ {+ headRefName: 'feat/own',+ identifier: 'lobehub/lobehub#7',+ linkedAt: '2026-11-18T00:00:00Z',+ source: 'branch',+ url: 'https://github.com/lobehub/lobehub/pull/7',+ vouched: false,+ },+ // Already a Work row: the Work wins.+ {+ identifier: 'lobehub/lobehub#1',+ linkedAt: '2026-11-19T00:00:00Z',+ source: 'manual',+ url: 'https://github.com/lobehub/lobehub/pull/1',+ vouched: true,+ },+ ],+ });++ const items = await listTopicPullRequestsWithStatus({+ db,+ topicId: 't1',+ topicModel,+ userId: 'u1',+ workModel,+ });++ expect(items.map((item) => [item.identifier, item.source, item.vouched])).toEqual([+ ['lobehub/lobehub#7', 'branch', false],+ ['lobehub/lobehub#1', 'created', true],+ ]);+ expect(items[0]).toMatchObject({ headBranch: 'feat/own', workId: null });});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 }),+ await listTopicPullRequestsWithStatus({+ db,+ topicId: 't1',+ topicModel: topicModelWith(),+ userId: 'u1',+ workModel,+ }),).toEqual([]);expect(listByIdentities).not.toHaveBeenCalled();});@@ -180,7 +233,7 @@ describe('linkPushedPullRequests', () => {expect.objectContaining({changeType: 'updated',messageId: 'msg-push',- metadata: { headBranch: 'feat/x' },+ metadata: { headBranch: 'feat/x', pullRequestLink: 'push' },patchFields: ['identifier', 'url', 'title', 'status'],resourceId: 'lobehub/lobehub#12',status: 'open',@@ -192,6 +245,26 @@ describe('linkPushedPullRequests', () => {);});+ it('accepts a fork PR whose head repository is the push destination', async () => {+ const models = createModels({+ ...pushRow,+ content: 'To github.com:contributor/lobehub.git\n 031bf96..f6b1c2a local -> feat/x',+ });++ const result = await link(models, [+ { ...devicePR, headRepoFullName: 'contributor/lobehub' },+ // A same-named branch in a stranger's fork was not this push.+ {+ ...devicePR,+ headRepoFullName: 'stranger/lobehub',+ number: 13,+ url: 'https://github.com/lobehub/lobehub/pull/13',+ },+ ]);++ expect(result).toEqual({ linked: ['lobehub/lobehub#12'], status: 'linked' });+ });+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' });diff --git a/apps/server/src/services/workRegistration/topicPullRequests.ts b/apps/server/src/services/workRegistration/topicPullRequests.tsindex 3f74feda082..1679ce87eca 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.ts@@ -3,12 +3,15 @@ import type {ScmCiStatus,ScmReviewDecision,TopicPullRequestItem,+ TopicPullRequestLinkMeta,TopicPullRequestScmState,+ TopicPullRequestWork,} from '@lobechat/types';import debug from 'debug';import type { MessageModel } from '@/database/models/message';import { ScmChangeRequestModel } from '@/database/models/scm';+import type { TopicModel } from '@/database/models/topic';import { parseGitPushResult, type WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';@@ -17,6 +20,7 @@ import {isBetterCodingExperienceEnabled,} from './pullRequestLinking';import { readShellCommandRecord } from './shellWorkRegistration';+import { parsePullRequestUrl } from './topicPullRequestLinks';const log = debug('lobe-server:topic-pull-requests');@@ -43,38 +47,79 @@ const toScmState = (row: ScmChangeRequestState): TopicPullRequestScmState => ({updatedAt: row.updatedAt,});+const toLinkItem = (link: TopicPullRequestLinkMeta): TopicPullRequestWork | null => {+ const parsed = parsePullRequestUrl(link.url);+ if (!parsed) return null;+ return {+ ...(link.headRefName ? { headBranch: link.headRefName } : {}),+ identifier: parsed.identifier,+ linkedAt: new Date(link.linkedAt),+ number: parsed.number,+ repoFullName: parsed.repoFullName,+ source: link.source,+ status: null,+ title: link.title ?? null,+ url: parsed.url,+ workId: null,+ };+};+/**- * 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.+ * Pull requests linked to a topic — its `github_pull_request` Work rows plus+ * the links kept on the topic (branch match, by hand), minus the ones removed+ * from it — latest link first, 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, vouched data may enable merge / close.*/export const listTopicPullRequestsWithStatus = async (params: {db: LobeChatDatabase;topicId: string;+ topicModel: TopicModel;userId: string;workModel: WorkModel;workspaceId?: string | null;}): Promise<TopicPullRequestItem[]> => {- const items = await params.workModel.listTopicPullRequests(params.topicId);+ const [works, topic] = await Promise.all([+ params.workModel.listTopicPullRequests(params.topicId),+ params.topicModel.findById(params.topicId),+ ]);+ const meta = topic?.metadata?.pullRequests;+ const dismissed = new Set((meta?.dismissed ?? []).map((id) => id.toLowerCase()));+ const fromWorks = new Set(works.map((item) => item.identifier.toLowerCase()));++ const items = [+ // Work rows were parsed by the server from the run's own tool messages.+ ...works.map((item) => ({ item, vouched: true })),+ ...(meta?.links ?? []).flatMap((link) => {+ const item = toLinkItem(link);+ return item && !fromWorks.has(item.identifier.toLowerCase())+ ? [{ item, vouched: link.vouched }]+ : [];+ }),+ ]+ .filter(({ item }) => !dismissed.has(item.identifier.toLowerCase()))+ .sort((a, b) => b.item.linkedAt.getTime() - a.item.linkedAt.getTime());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 })),+ items.map(({ item }) => ({ number: item.number, repoFullName: item.repoFullName })),);const byIdentity = new Map(rows.map((row) => [identityKey(row.repoFullName, row.number), row]));- return items.map((item) => {+ return items.map(({ item, vouched }) => {const row = byIdentity.get(identityKey(item.repoFullName, item.number));- return { ...item, scm: row ? toScmState(row) : null };+ return { ...item, scm: row ? toScmState(row) : null, vouched };});};/** One pull request the execution device found for a pushed branch (`gh pr list --head`). */export interface DeviceReportedPullRequest {headRefName: string;+ /** `owner/repo` of the PR's head branch, from devices that report it. */+ headRepoFullName?: string;isDraft?: boolean;number: number;state?: string;@@ -167,7 +212,11 @@ export const linkPushedPullRequests = async (params: {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 [];+ // The push went to the PR's head repository: the PR's own repository,+ // or — for a fork PR — the fork its head lives in.+ const pushed = push.repoFullName.toLowerCase();+ const headRepo = (pr.headRepoFullName ?? repoFullName).toLowerCase();+ if (headRepo !== pushed) return [];if (!branches.has(pr.headRefName)) return [];return [{@@ -198,7 +247,10 @@ export const linkPushedPullRequests = async (params: {changeType: 'updated',identifier,messageId: record.id,- ...(pr.headRef ? { metadata: { headBranch: pr.headRef } } : {}),+ metadata: {+ ...(pr.headRef ? { headBranch: pr.headRef } : {}),+ pullRequestLink: 'push',+ },patchFields: ['identifier','url',diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9b1590299ca..179debc1e6d 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3748,6 +3748,16 @@"workingPanel.overview.ports.revoked": "Sharing stopped","workingPanel.overview.ports.title": "Ports","workingPanel.overview.ports.unavailable": "Can't read this device's ports right now",+ "workingPanel.overview.pr.dismiss": "Remove from this topic",+ "workingPanel.overview.pr.dismissFailed": "Couldn't remove {{name}} from this topic",+ "workingPanel.overview.pr.dismissed": "Removed {{name}} from this topic",+ "workingPanel.overview.pr.link": "Link a pull request",+ "workingPanel.overview.pr.linkAction": "Link",+ "workingPanel.overview.pr.linkFailed": "Couldn't link the pull request",+ "workingPanel.overview.pr.linkInvalid": "Paste a GitHub pull request link, like https://github.com/owner/repo/pull/123",+ "workingPanel.overview.pr.linkPlaceholder": "Paste a GitHub pull request link",+ "workingPanel.overview.pr.linked": "Linked {{name}} to this topic",+ "workingPanel.overview.pr.unvouched": "Can't confirm this PR comes from this topic's branch, so merging and closing are locked","workingPanel.overview.subagents": "Subagents","workingPanel.overview.subtopics": "Subtopics","workingPanel.overview.sync.ahead_one": "{{count}} commit ahead",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ed13023e3a4..acc77088610 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3748,6 +3748,16 @@"workingPanel.overview.ports.revoked": "已停止共享","workingPanel.overview.ports.title": "端口","workingPanel.overview.ports.unavailable": "暂时无法读取这台设备的端口",+ "workingPanel.overview.pr.dismiss": "从话题中移除",+ "workingPanel.overview.pr.dismissFailed": "未能将 {{name}} 从话题中移除",+ "workingPanel.overview.pr.dismissed": "已将 {{name}} 从话题中移除",+ "workingPanel.overview.pr.link": "关联 PR",+ "workingPanel.overview.pr.linkAction": "关联",+ "workingPanel.overview.pr.linkFailed": "关联 PR 失败",+ "workingPanel.overview.pr.linkInvalid": "请粘贴 GitHub PR 链接,例如 https://github.com/owner/repo/pull/123",+ "workingPanel.overview.pr.linkPlaceholder": "粘贴 GitHub PR 链接",+ "workingPanel.overview.pr.linked": "已将 {{name}} 关联到话题",+ "workingPanel.overview.pr.unvouched": "无法确认这个 PR 来自本话题的分支,合并和关闭已锁定","workingPanel.overview.subagents": "子代理","workingPanel.overview.subtopics": "子话题","workingPanel.overview.sync.ahead_one": "领先 {{count}} 个提交",diff --git a/packages/database/src/models/work/__tests__/github.test.ts b/packages/database/src/models/work/__tests__/github.test.tsindex e4edf2b28c5..ad83a084ee8 100644--- a/packages/database/src/models/work/__tests__/github.test.ts+++ b/packages/database/src/models/work/__tests__/github.test.ts@@ -443,9 +443,9 @@ describe('WorkModel · github', () => {const versions = await workModel.listVersions(created!.id);expect(versions.map((item) => [item.version, item.metadata])).toEqual([- [3, { baseBranch: 'main', headBranch: 'feat/branch-card' }],- [2, { baseBranch: 'canary', headBranch: 'feat/branch-card' }],- [1, { baseBranch: 'canary', headBranch: 'feat/branch-card' }],+ [3, { baseBranch: 'main', headBranch: 'feat/branch-card', pullRequestLink: 'command' }],+ [2, { baseBranch: 'canary', headBranch: 'feat/branch-card', pullRequestLink: 'command' }],+ [1, { baseBranch: 'canary', headBranch: 'feat/branch-card', pullRequestLink: 'command' }],]);// Summary cards render the current version, so an older message's card@@ -454,6 +454,10 @@ describe('WorkModel · github', () => {rootOperationIds: ['op-pr-branch-retitle'],});const summary = expectExternalSummaryItem(byOperation['op-pr-branch-retitle']?.[0]);- expect(summary.event.metadata).toEqual({ baseBranch: 'main', headBranch: 'feat/branch-card' });+ expect(summary.event.metadata).toEqual({+ baseBranch: 'main',+ headBranch: 'feat/branch-card',+ pullRequestLink: 'command',+ });});});diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.tsindex 7f3c3600bd8..3986379eaa9 100644--- a/packages/database/src/models/work/__tests__/githubToolResult.test.ts+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts@@ -497,14 +497,22 @@ describe('normalizeGithubToolResult (structured REST results)', () => {undefined,'create_pull_request',);- expect(fromRefs?.params.metadata).toEqual({ baseBranch: 'canary', headBranch: 'feat/x' });+ expect(fromRefs?.params.metadata).toEqual({+ baseBranch: 'canary',+ headBranch: 'feat/x',+ pullRequestLink: 'command',+ });const fromArgs = structured({ number: 22, repository_full_name: 'lobehub/lobehub' },{ base: 'main', head: 'feat/y' },'create_pull_request',);- expect(fromArgs?.params.metadata).toEqual({ baseBranch: 'main', headBranch: 'feat/y' });+ expect(fromArgs?.params.metadata).toEqual({+ baseBranch: 'main',+ headBranch: 'feat/y',+ pullRequestLink: 'command',+ });const issue = structured({ base: { ref: 'main' }, number: 23, repository_full_name: 'lobehub/lobehub' },@@ -692,21 +700,30 @@ describe('normalizeGithubToolResult (gh CLI edge cases)', () => {`gh pr create --repo lobehub/lobehub --head feat/work-branch --base=canary --title 'T' --body-file /tmp/body.md`,'https://github.com/lobehub/lobehub/pull/11',);- expect(long?.params.metadata).toEqual({ baseBranch: 'canary', headBranch: 'feat/work-branch' });+ expect(long?.params.metadata).toEqual({+ baseBranch: 'canary',+ headBranch: 'feat/work-branch',+ pullRequestLink: 'command',+ });const short = runCommand(`gh pr create -R lobehub/lobehub -H fork-owner:fix/x -B main -t 'T'`,'https://github.com/lobehub/lobehub/pull/12',);- expect(short?.params.metadata).toEqual({ baseBranch: 'main', headBranch: 'fork-owner:fix/x' });+ expect(short?.params.metadata).toEqual({+ baseBranch: 'main',+ headBranch: 'fork-owner:fix/x',+ pullRequestLink: 'command',+ });});it('records only the base a `gh pr edit --base` changes, and nothing without branch flags', () => {const retarget = runCommand(`gh pr edit 13 --repo lobehub/lobehub --base main`);- expect(retarget?.params.metadata).toEqual({ baseBranch: 'main' });+ expect(retarget?.params.metadata).toEqual({ baseBranch: 'main', pullRequestLink: 'command' });const retitle = runCommand(`gh pr edit 13 --repo lobehub/lobehub --title 'Retitled'`);- expect(retitle?.params.metadata).toBeUndefined();+ // No branch flag: only the command marker, so the create-time branches survive the merge.+ expect(retitle?.params.metadata).toEqual({ pullRequestLink: 'command' });});it('never attaches branches to an issue', () => {diff --git a/packages/database/src/models/work/__tests__/pullRequests.test.ts b/packages/database/src/models/work/__tests__/pullRequests.test.tsindex 887ce400546..cb3b72ef001 100644--- a/packages/database/src/models/work/__tests__/pullRequests.test.ts+++ b/packages/database/src/models/work/__tests__/pullRequests.test.ts@@ -112,4 +112,52 @@ describe('WorkModel.listTopicPullRequests', () => {'lobehub/lobehub#7',]);});++ it('reports how the topic linked each PR', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerExternal(pr('lobehub/lobehub#10', 'call-create'));+ await model.registerExternal(+ pr('lobehub/lobehub#11', 'call-merge', {+ changeType: 'updated',+ patchFields: ['identifier'],+ }),+ );+ await model.registerExternal(+ pr('lobehub/lobehub#12', 'call-push', {+ changeType: 'updated',+ metadata: { headBranch: 'feat/p', pullRequestLink: 'push' },+ patchFields: ['identifier'],+ }),+ );++ const sources = Object.fromEntries(+ (await model.listTopicPullRequests(topicId)).map((i) => [i.number, i.source]),+ );+ expect(sources).toEqual({ 10: 'created', 11: 'command', 12: 'push' });+ });++ it('reports a PR first linked by a push as command once a command names it', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerExternal(+ pr('lobehub/lobehub#20', 'call-push', {+ changeType: 'updated',+ metadata: { headBranch: 'feat/p', pullRequestLink: 'push' },+ patchFields: ['identifier'],+ }),+ );+ // gh pr edit 20: the normalizer stamps its own marker over the merged metadata.+ await model.registerExternal(+ pr('lobehub/lobehub#20', 'call-edit', {+ changeType: 'updated',+ metadata: { pullRequestLink: 'command' },+ patchFields: ['identifier', 'title'],+ }),+ );++ expect((await model.listTopicPullRequests(topicId))[0]).toMatchObject({+ headBranch: 'feat/p',+ number: 20,+ source: 'command',+ });+ });});diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.tsindex 2232be4dd83..b9eda813805 100644--- a/packages/database/src/models/work/githubToolResult.ts+++ b/packages/database/src/models/work/githubToolResult.ts@@ -212,6 +212,16 @@ const branchMetadata = (return { ...(head && { headBranch: head }), ...(base && { baseBranch: base }) };};+/**+ * A PR version registered from a command that named the PR. Version metadata+ * merges over the previous version's, so without its own marker it would+ * inherit `pullRequestLink: 'push'` from an earlier push link.+ */+const pullRequestCommandMetadata = (+ head: string | null,+ base: string | null,+): WorkVersionMetadata => ({ ...branchMetadata(head, base), pullRequestLink: 'command' });+/*** A REST pull request carries `head` / `base` as `{ ref }` objects; the* `create_pull_request` arguments name them as plain strings.@@ -258,7 +268,10 @@ const buildParams = (messageId: params.messageId ?? null,metadata:tool.entityType === 'pull_request'- ? branchMetadata(resolveBranch(record, args, 'head'), resolveBranch(record, args, 'base'))+ ? pullRequestCommandMetadata(+ resolveBranch(record, args, 'head'),+ resolveBranch(record, args, 'base'),+ ): undefined,rootOperationId: params.rootOperationId ?? null,status: patch('status', hasStatusSignal(record), resolveStatus(record)),@@ -643,7 +656,10 @@ const normalizeGithubCliResult = (resourceId: identifier,resourceType: githubResourceType(ref.entityType),messageId: params.messageId ?? null,- metadata: branchMetadata(parsed.head, parsed.base),+ metadata:+ ref.entityType === 'pull_request'+ ? pullRequestCommandMetadata(parsed.head, parsed.base)+ : undefined,rootOperationId: params.rootOperationId ?? null,// gh only exposes --draft on create; an edit carries no status signal,// while merge / ready say what they left the pull request in.diff --git a/packages/database/src/models/work/pullRequests.ts b/packages/database/src/models/work/pullRequests.tsindex 82092c4a9cc..4881d9591e6 100644--- a/packages/database/src/models/work/pullRequests.ts+++ b/packages/database/src/models/work/pullRequests.ts@@ -1,4 +1,8 @@-import type { TopicPullRequestWork, WorkVersionMetadata } from '@lobechat/types';+import type {+ TopicPullRequestLinkSource,+ TopicPullRequestWork,+ WorkVersionMetadata,+} from '@lobechat/types';import { and, desc, eq, inArray, isNotNull, sql } from 'drizzle-orm';import { works, workVersions } from '../../schemas/work';@@ -25,10 +29,16 @@ export const listTopicPullRequests = async (topicId: string,): Promise<TopicPullRequestWork[]> => {const linkedAt = sql<Date>`max(${workVersions.createdAt})`;+ // How the topic came to it: an open command here (`gh pr create`) beats a+ // command naming it, which beats only ever having pushed to its branch.+ const created = sql<boolean>`bool_or(${workVersions.changeType} = 'created')`;+ const pushOnly = sql<boolean>`bool_and(coalesce(${workVersions.metadata} ->> 'pullRequestLink', '') = 'push')`;const rows = await ctx.db.select({+ created,currentVersionId: works.currentVersionId,linkedAt,+ pushOnly,resourceId: works.resourceId,status: works.status,title: works.title,@@ -75,6 +85,11 @@ export const listTopicPullRequests = async (linkedAt: new Date(row.linkedAt),number: identity.number,repoFullName: identity.repoFullName,+ source: (row.created+ ? 'created'+ : row.pushOnly+ ? 'push'+ : 'command') satisfies TopicPullRequestLinkSource,status: row.status,title: row.title,url: row.url,diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 473653f0ba4..2cf290ba45b 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -379,7 +379,12 @@ export const executeDeviceRpc = async (case 'getLinkedPullRequest': {return getLinkedPullRequest(- params as { branch: string; path: string; pullRequestNumber?: number },+ params as {+ branch: string;+ path: string;+ pullRequestNumber?: number;+ state?: 'all' | 'open';+ },);}diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.tsindex 7b59df89f49..7c3c61d2163 100644--- a/packages/electron-client-ipc/src/types/git.ts+++ b/packages/electron-client-ipc/src/types/git.ts@@ -23,6 +23,10 @@ export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknowexport interface GitLinkedPullRequest {ciStatus?: GitPullRequestCiStatus;+ /** The PR's head branch on GitHub */+ headRefName?: string;+ /** `owner/repo` of the PR's head branch — not the PR's own repo for a fork PR */+ headRepoFullName?: string;isDraft?: boolean;mergeable?: string;mergedAt?: string | null;@@ -41,6 +45,8 @@ export interface GitLinkedPullRequestResult {extraCount?: number;/** Null when no PR is linked to the branch */pullRequest: GitLinkedPullRequest | null;+ /** `owner/repo` of the GitHub remote the branch publishes to, when it is one */+ remoteRepoFullName?: string;/** 'ok' — lookup succeeded; 'gh-missing' — gh CLI unavailable / not authed; 'error' — other failure */status: GitLinkedPullRequestLookupStatus;/** Remote ref the lookup queried under — the PR's own head ref when one was found */diff --git a/packages/local-file-shell/src/git/__tests__/info.test.ts b/packages/local-file-shell/src/git/__tests__/info.test.tsindex c0f6332822d..05644cc8417 100644--- a/packages/local-file-shell/src/git/__tests__/info.test.ts+++ b/packages/local-file-shell/src/git/__tests__/info.test.ts@@ -39,6 +39,7 @@ const PULL_REQUEST = {const NORMALIZED_PULL_REQUEST = {ciStatus: 'success',+ headRefName: 'feat/hetero-session-import-ui',isDraft: false,mergeStateStatus: 'CLEAN',mergeable: 'MERGEABLE',@@ -57,6 +58,8 @@ interface ShellFixture {commitOnDefault?: boolean;/** `gh api repos/{owner}/{repo}/commits/<sha>/pulls`. */commitPulls?: unknown[];+ /** `git config --get <key>`. */+ config?: Record<string, string>;defaultBranch?: Record<string, string>;/** `gh pr list --head`. */prList?: unknown[];@@ -66,6 +69,10 @@ interface ShellFixture {pushedRefs?: string[];refsAt?: string[];remotes?: string[];+ /** `git remote get-url --push <remote>`. */+ remoteUrl?: string;+ /** Per-remote push URLs, overriding {@link remoteUrl}. */+ remoteUrls?: Record<string, string>;/** Remote refs a local branch tracks (`for-each-ref --format=%(upstream)`). */trackedRefs?: string[];}@@ -92,11 +99,21 @@ const mockShell = ({pushedRefs = [],refsAt = [],remotes = ['origin'],+ config = {},+ remoteUrl = '',+ remoteUrls = {},trackedRefs = [],}: ShellFixture) => {childProcessMocks.execFileAsync.mockImplementation(async (cmd: string, args: string[]) => {if (cmd === 'git') {const [subcommand] = args;+ if (subcommand === 'remote' && args[1] === 'get-url')+ return ok(remoteUrls[args.at(-1)!] ?? remoteUrl);+ if (subcommand === 'config') {+ const value = config[args.at(-1)!];+ if (value === undefined) throw Object.assign(new Error('unset'), { code: 1 });+ return ok(value);+ }if (subcommand === 'remote') return ok(remotes.join('\n'));if (subcommand === 'merge-base') {// `--is-ancestor` reports through the exit status: 0 = contained, 1 = not.@@ -172,7 +189,7 @@ describe('getLinkedPullRequest', () => {);expect(result).toEqual({extraCount: 0,- pullRequest: NORMALIZED_PULL_REQUEST,+ pullRequest: { ...NORMALIZED_PULL_REQUEST, headRefName: 'fix/topic-running' },status: 'ok',upstream: { branch: 'fix/topic-running', remote: 'origin' },});@@ -180,6 +197,84 @@ describe('getLinkedPullRequest', () => {// The reported bug. The local branch name never existed on the remote, so asking// `gh` about it returned an empty list forever and the PR silently never linked.+ it("reports the PR's head repository and the repository the checkout publishes to", async () => {+ mockShell({+ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x',+ prList: [+ {+ ...PULL_REQUEST,+ headRefName: 'feat/x',+ headRepository: { name: 'lobehub' },+ headRepositoryOwner: { login: 'contributor' },+ },+ ],+ remoteUrl: '[email protected]:contributor/lobehub.git\n',+ });++ const result = await getLinkedPullRequest({ branch: 'feat/x', path: '/repo' });++ expect(result.remoteRepoFullName).toBe('contributor/lobehub');+ expect(result.pullRequest).toMatchObject({+ headRefName: 'feat/x',+ headRepoFullName: 'contributor/lobehub',+ });+ expect(childProcessMocks.execFileAsync).toHaveBeenCalledWith(+ 'gh',+ expect.arrayContaining([expect.stringContaining('headRepositoryOwner')]),+ expect.anything(),+ );+ });++ it('names the push remote of a triangular workflow, not the upstream it pulls from', async () => {+ mockShell({+ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x',+ config: { 'branch.feat/x.pushRemote': 'fork' },+ prList: [],+ remoteUrls: {+ fork: '[email protected]:alice/widgets.git\n',+ origin: '[email protected]:acme/widgets.git\n',+ },+ });++ expect(+ (await getLinkedPullRequest({ branch: 'feat/x', path: '/repo' })).remoteRepoFullName,+ ).toBe('alice/widgets');++ mockShell({+ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x',+ config: { 'remote.pushDefault': 'fork' },+ prList: [],+ remoteUrls: { fork: 'https://github.com/alice/widgets.git\n' },+ });+ expect(+ (await getLinkedPullRequest({ branch: 'feat/x', path: '/repo' })).remoteRepoFullName,+ ).toBe('alice/widgets');+ });++ it('lists only open PRs when asked, so a newer closed PR cannot hide the open one', async () => {+ mockShell({ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x', prList: [] });++ await getLinkedPullRequest({ branch: 'feat/x', path: '/repo', state: 'open' });++ expect(childProcessMocks.execFileAsync).toHaveBeenCalledWith(+ 'gh',+ expect.arrayContaining(['--head', 'feat/x', '--state', 'open']),+ expect.anything(),+ );+ });++ it('names no remote repository for a non-GitHub remote', async () => {+ mockShell({+ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x',+ prList: [],+ remoteUrl: 'https://gitlab.com/a/b.git\n',+ });++ expect(+ (await getLinkedPullRequest({ branch: 'feat/x', path: '/repo' })).remoteRepoFullName,+ ).toBeUndefined();+ });+it('queries the head branch that exists on the REMOTE, not the local branch name', async () => {mockShell({...publishedAs('refs/remotes/origin/feat/hetero-session-import-ui'),diff --git a/packages/local-file-shell/src/git/info.ts b/packages/local-file-shell/src/git/info.tsindex cb41cf19a49..e6d36ff5293 100644--- a/packages/local-file-shell/src/git/info.ts+++ b/packages/local-file-shell/src/git/info.ts@@ -15,7 +15,13 @@ import type {GitUpstreamRef,GitWorkingTreeStatus,} from './types';-import { getDefaultRemote, isCommitSafeForPullRequestLookup, resolveUpstream } from './upstream';+import {+ getDefaultRemote,+ getPushRemote,+ getRemoteGithubRepo,+ isCommitSafeForPullRequestLookup,+ resolveUpstream,+} from './upstream';const log = createLogger('local-file-shell:git');const execFileAsync = promisify(execFile);@@ -29,6 +35,8 @@ type GithubStatusCheckRollupNode = {type GithubPullRequestPayload = {/** The PR's head branch ON GitHub — the authoritative remote ref for this branch. */headRefName?: string | null;+ headRepository?: { name?: string | null } | null;+ headRepositoryOwner?: { login?: string | null } | null;isDraft?: boolean;mergeable?: string | null;mergeStateStatus?: string | null;@@ -42,7 +50,7 @@ type GithubPullRequestPayload = {};const GITHUB_PULL_REQUEST_FIELDS =- 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup,headRefName';+ 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup,headRefName,headRepository,headRepositoryOwner';const failureConclusions = new Set(['action_required',@@ -107,9 +115,15 @@ const normalizeGithubPullRequest = (pr: GithubPullRequestPayload): GitLinkedPullconst mergeable = compactString(pr.mergeable);const mergeStateStatus = compactString(pr.mergeStateStatus);const reviewDecision = compactString(pr.reviewDecision);+ const headRefName = compactString(pr.headRefName);+ const headOwner = pr.headRepositoryOwner?.login;+ const headName = pr.headRepository?.name;+ const headRepoFullName = headOwner && headName ? `${headOwner}/${headName}` : undefined;return {...(ciStatus ? { ciStatus } : {}),+ ...(headRefName ? { headRefName } : {}),+ ...(headRepoFullName ? { headRepoFullName } : {}),...(pr.isDraft === undefined ? {} : { isDraft: pr.isDraft }),...(mergeable ? { mergeable } : {}),...(mergeStateStatus ? { mergeStateStatus } : {}),@@ -222,8 +236,10 @@ export const getLinkedPullRequest = async (payload: {branch: string;path: string;pullRequestNumber?: number;+ /** `open` lists only open PRs (discovery); default `all` also refreshes merged / closed ones. */+ state?: 'all' | 'open';}): Promise<GitLinkedPullRequestResult> => {- const { path: dirPath, branch, pullRequestNumber } = payload;+ const { path: dirPath, branch, pullRequestNumber, state = 'all' } = payload;if (!branch && pullRequestNumber === undefined) return { pullRequest: null, status: 'ok' };const viewPullRequest = async (number: number): Promise<GithubPullRequestPayload> => {@@ -241,15 +257,24 @@ export const getLinkedPullRequest = async (payload: {const { sha, upstream: localUpstream } = branch? await resolveUpstream(dirPath, branch): { sha: undefined, upstream: undefined };+ // The repository this checkout publishes to: a found PR whose head lives+ // here was pushed from here, not a same-named branch in another fork.+ const remote =+ (await getPushRemote(dirPath, branch || undefined)) ??+ localUpstream?.remote ??+ (await getDefaultRemote(dirPath));+ const remoteRepoFullName = remote ? await getRemoteGithubRepo(dirPath, remote) : undefined;+ const answer = (result: GitLinkedPullRequestResult): GitLinkedPullRequestResult =>+ remoteRepoFullName ? { ...result, remoteRepoFullName } : result;if (pullRequestNumber !== undefined) {const parsed = await viewPullRequest(pullRequestNumber);const upstream = await toUpstreamRef(dirPath, parsed.headRefName, localUpstream);- return {+ return answer({pullRequest: normalizeGithubPullRequest(parsed),status: 'ok',...(upstream ? { upstream } : {}),- };+ });}const { stdout } = await execFileAsync(@@ -260,7 +285,7 @@ export const getLinkedPullRequest = async (payload: {'--head',localUpstream?.branch ?? branch,'--state',- 'all',+ state,'--limit','5','--json',@@ -273,12 +298,12 @@ export const getLinkedPullRequest = async (payload: {if (parsed.length > 0) {const [primaryRaw, ...rest] = parsed;const upstream = await toUpstreamRef(dirPath, primaryRaw.headRefName, localUpstream);- return {+ return answer({extraCount: rest.length,pullRequest: normalizeGithubPullRequest(primaryRaw),status: 'ok',...(upstream ? { upstream } : {}),- };+ });}// Empty. With a resolved remote ref that is a real answer — the branch has no PR.@@ -289,19 +314,19 @@ export const getLinkedPullRequest = async (payload: {const recovered = await findPullRequestByCommit(dirPath, sha);if (recovered) {const upstream = await toUpstreamRef(dirPath, recovered.headRefName);- return {+ return answer({pullRequest: normalizeGithubPullRequest(await viewPullRequest(recovered.number)),status: 'ok',...(upstream ? { upstream } : {}),- };+ });}}- return {+ return answer({pullRequest: null,status: 'ok',...(localUpstream ? { upstream: localUpstream } : {}),- };+ });} catch (error: any) {const code = error?.code;const stderr: string = error?.stderr ?? '';diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.tsindex f50cef5112c..718f3e90886 100644--- a/packages/local-file-shell/src/git/types.ts+++ b/packages/local-file-shell/src/git/types.ts@@ -24,6 +24,10 @@ export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknowexport interface GitLinkedPullRequest {ciStatus?: GitPullRequestCiStatus;+ /** The PR's head branch on GitHub. */+ headRefName?: string;+ /** `owner/repo` of the PR's head branch — not the PR's own repo for a fork PR. */+ headRepoFullName?: string;isDraft?: boolean;mergeable?: string;mergedAt?: string | null;@@ -42,6 +46,8 @@ export interface GitLinkedPullRequestResult {extraCount?: number;/** Null when no PR is linked to the branch. */pullRequest: GitLinkedPullRequest | null;+ /** `owner/repo` of the GitHub remote the branch publishes to, when it is one. */+ remoteRepoFullName?: string;/** 'ok' — succeeded; 'gh-missing' — gh CLI unavailable / not authed; 'error' — other. */status: GitLinkedPullRequestLookupStatus;/**diff --git a/packages/local-file-shell/src/git/upstream.ts b/packages/local-file-shell/src/git/upstream.tsindex d2844d7e949..173b400ca61 100644--- a/packages/local-file-shell/src/git/upstream.ts+++ b/packages/local-file-shell/src/git/upstream.ts@@ -268,6 +268,40 @@ export const getDefaultRemote = async (dirPath: string): Promise<string | undefireturn remotes[0];};+/**+ * git remote URL forms that name a GitHub repository: https (with or without+ * credentials), ssh://, and scp-like `[email protected]:owner/repo.git`.+ */+const GITHUB_REMOTE_RE =+ /^(?:https?:\/\/(?:[^@/\s]+@)?github\.com\/|ssh:\/\/(?:[^@/\s]+@)?github\.com(?::\d+)?\/|(?:[^@/\s]+@)?github\.com:)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i;++/**+ * The remote a branch PUSHES to when it differs from where it pulls: a+ * triangular workflow tracks `origin` but publishes to a fork. Git resolves it+ * from `branch.<name>.pushRemote`, then `remote.pushDefault`; undefined when+ * neither is set (the upstream remote is then the push remote too).+ */+export const getPushRemote = async (+ dirPath: string,+ branch?: string,+): Promise<string | undefined> => {+ const read = async (key: string) =>+ (await runGit(['config', '--get', key], dirPath))?.trim() || undefined;+ return (+ (branch ? await read(`branch.${branch}.pushRemote`) : undefined) ?? read('remote.pushDefault')+ );+};++/** `owner/repo` of a remote's GitHub push URL; undefined for any other host. */+export const getRemoteGithubRepo = async (+ dirPath: string,+ remote: string,+): Promise<string | undefined> => {+ const url = (await runGit(['remote', 'get-url', '--push', remote], dirPath))?.trim();+ const match = url ? GITHUB_REMOTE_RE.exec(url) : null;+ return match ? `${match[1]}/${match[2]}` : undefined;+};+/** Exit-status-only probe — `runGit` cannot tell success-with-no-output from failure. */const gitSucceeds = async (args: string[], cwd: string): Promise<boolean> => {try {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c0370e0a21a..e927c6f01cf 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3920,6 +3920,18 @@ export default {'workingPanel.overview.changes': 'Changes','workingPanel.overview.changes.none': 'No changes','workingPanel.overview.ci.failure': 'Failed',+ 'workingPanel.overview.pr.dismiss': 'Remove from this topic',+ 'workingPanel.overview.pr.dismissFailed': "Couldn't remove {{name}} from this topic",+ 'workingPanel.overview.pr.dismissed': 'Removed {{name}} from this topic',+ 'workingPanel.overview.pr.link': 'Link a pull request',+ 'workingPanel.overview.pr.linkAction': 'Link',+ 'workingPanel.overview.pr.linkFailed': "Couldn't link the pull request",+ 'workingPanel.overview.pr.linkInvalid':+ 'Paste a GitHub pull request link, like https://github.com/owner/repo/pull/123',+ 'workingPanel.overview.pr.linkPlaceholder': 'Paste a GitHub pull request link',+ 'workingPanel.overview.pr.linked': 'Linked {{name}} to this topic',+ 'workingPanel.overview.pr.unvouched':+ "Can't confirm this PR comes from this topic's branch, so merging and closing are locked",'workingPanel.overview.ci.pending': 'Running','workingPanel.overview.empty':'Workspace activity and outputs will appear here as the agent works.',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 408680cdc15..8dc54c4657b 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -353,6 +353,12 @@ export interface DeviceGitLinkedPullRequestResult {extraCount?: number;/** Null when no PR is linked to the branch. */pullRequest: DeviceGitLinkedPullRequest | null;+ /**+ * `owner/repo` of the GitHub remote the branch publishes to. A PR whose head+ * repository is this one was pushed from here; a same-named branch in+ * another fork was not. Absent from devices that predate it.+ */+ remoteRepoFullName?: string;/** 'ok' — lookup succeeded; 'gh-missing' — gh CLI unavailable; 'error' — other failure. */status: DeviceGitLinkedPullRequestLookupStatus;/** Remote ref the lookup queried under — the PR's own head ref when one was found. */diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex a13d72dd7f5..16de7a4e324 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -15,6 +15,7 @@ import type { BaseDataModel } from '../meta';import type { OwnedWorktree } from '../ownedWorktree';import type { OnboardingUnderstandingSession } from '../understanding';import type { OnboardingTaskRecommendationSession } from '../user/onboardingTasks';+import type { TopicPullRequestsMeta } from '../work';export type ShareVisibility = 'private' | 'link';export type TimeGroupId =@@ -154,8 +155,8 @@ export interface ChatTopicMetadata {summarizedAt?: string;version: number;};-bot?: ChatTopicBotContext;+botCreator?: BotSenderMetadata | null;boundDeviceId?: string;cronJobId?: string;@@ -311,6 +312,13 @@ export interface ChatTopicMetadata {ownedWorktrees?: OwnedWorktree[];/** Measured dominant provider by token volume — see {@link ChatTopicMetadata.model}. */provider?: string;+ /**+ * Better Coding Experience: PR links kept on the topic (found on its own+ * branch, or linked by hand) and the PRs removed from its lists. Server-owned —+ * written only by the `work.*TopicPullRequest` endpoints, never by a client+ * metadata patch.+ */+ pullRequests?: TopicPullRequestsMeta;/*** Topic-pinned reasoning effort / mode for the pinned API model* (`ChatTopic.model`). Mirrors the model pin: snapshotted from the user'sdiff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex da62b1beb95..f03188f77fe 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -145,6 +145,12 @@ export interface WorkVersionMetadata {linesDeleted?: number;/** `file` Work — MIME type of the edited file. */mimeType?: string;+ /**+ * `external` GitHub PR Work — how this version linked the PR: `command` when+ * a command named it, `push` for a `git push` to a branch that already had+ * it. Set on every version, since metadata merges over the previous one.+ */+ pullRequestLink?: 'command' | 'push';}export interface WorkVersionCumulativeUsage {@@ -657,10 +663,48 @@ export type WorkRegistrationIntent =};/**- * 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.+ * How a pull request came to be linked to a topic, strongest first:+ *+ * - `created` — the topic's agent opened it (`gh pr create`).+ * - `command` — the agent ran a command naming it (`gh pr edit|ready|merge <n>`).+ * - `push` — the agent pushed to a branch that already had it.+ * - `branch` — found on a branch the topic created (run-end lookup).+ * - `manual` — the person linked it by URL.+ *+ * The first three are Work rows the server parsed from the run's own tool+ * messages; `branch` and `manual` are topic links that only drive the UI.+ */+export type TopicPullRequestLinkSource = 'branch' | 'command' | 'created' | 'manual' | 'push';++/**+ * A link kept on the topic itself (`metadata.pullRequests.links`) rather than+ * as a Work row: a PR found on the topic's own branch, or linked by hand.+ * Written only by the server's link endpoints.+ */+export interface TopicPullRequestLinkMeta {+ headRefName?: string;+ /** `owner/repo#number`. */+ identifier: string;+ /** ISO time it was linked. */+ linkedAt: string;+ source: 'branch' | 'manual';+ title?: string;+ url: string;+ /** See {@link TopicPullRequestItem.vouched}. */+ vouched: boolean;+}++/** Topic-level PR links and the PRs a person removed from the topic's lists. */+export interface TopicPullRequestsMeta {+ /** `owner/repo#number` hidden from the topic; the Work rows stay. */+ dismissed?: string[];+ links?: TopicPullRequestLinkMeta[];+}++/**+ * One GitHub pull request linked to a topic (Better Coding Experience): by any+ * `work_versions` row of a `github_pull_request` Work with that `topicId`, or by+ * a topic link (branch match / by hand). A topic can carry several.*/export interface TopicPullRequestWork {baseBranch?: string;@@ -671,11 +715,14 @@ export interface TopicPullRequestWork {linkedAt: Date;number: number;repoFullName: string;+ /** See {@link TopicPullRequestLinkSource}. */+ source: TopicPullRequestLinkSource;/** Status the agent's own commands left it in (`open`, `draft`, `merged`). */status: string | null;title: string | null;url: string | null;- workId: string;+ /** Null for a topic link with no Work row. */+ workId: string | null;}/**@@ -695,4 +742,11 @@ export interface TopicPullRequestScmState {export interface TopicPullRequestItem extends TopicPullRequestWork {scm: TopicPullRequestScmState | null;+ /**+ * Whether the app can vouch this PR belongs to the topic: the run's own+ * commands named it, the person linked it, or the branch match found its head+ * in the repository the topic pushes to. An unvouched PR is listed but its+ * merge / close stay locked.+ */+ vouched: boolean;}diff --git a/packages/types/src/workingDir.ts b/packages/types/src/workingDir.tsindex d8027d98fc9..e28db19bd4c 100644--- a/packages/types/src/workingDir.ts+++ b/packages/types/src/workingDir.ts@@ -20,6 +20,13 @@ export type DeviceGitPullRequestCiStatus = 'failure' | 'pending' | 'success' | '/** A GitHub pull request linked to a branch. */export interface DeviceGitLinkedPullRequest {ciStatus?: DeviceGitPullRequestCiStatus;+ /** The PR's head branch on GitHub. */+ headRefName?: string;+ /**+ * `owner/repo` the PR's head branch lives in — differs from the PR's own+ * repository for a fork PR. Absent from devices that predate it.+ */+ headRepoFullName?: string;isDraft?: boolean;mergeable?: string;mergedAt?: string | null;@@ -89,6 +96,14 @@ export interface WorkingDirGitState {* the source path itself.*/isWorktree?: boolean;+ /**+ * A branch this conversation created — the worktree branch made on its first+ * send (Better Coding Experience), or one its agent created+ * (`git switch -c`, `git worktree add -b`). Only while the topic is on it does+ * the run end ask GitHub which PR the branch has: another branch may carry+ * someone else's PR.+ */+ ownBranch?: string;/** The nonce the server signed {@link ownerToken} with, for the creator only. */ownerNonce?: string;/**@@ -180,6 +195,8 @@ export const getWorkingDirSessionPath = (const gitLinkedPullRequestSchema = z.object({ciStatus: z.enum(['failure', 'pending', 'success', 'unknown']).optional(),+ headRefName: z.string().optional(),+ headRepoFullName: z.string().optional(),isDraft: z.boolean().optional(),mergeable: z.string().optional(),mergeStateStatus: z.string().optional(),@@ -208,6 +225,7 @@ export const workingDirConfigSchema = z.object({}).optional(),isWorktree: z.boolean().optional(),+ ownBranch: z.string().optional(),ownerNonce: z.string().max(64).optional(),ownerToken: z.string().max(128).optional(),// Mirrors `WorkingDirGitState.upstream`. A field missing here is not merelydiff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.tsindex 70bea22bbde..28fd09355aa 100644--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts@@ -380,6 +380,8 @@ describe('prepareDraftGitSend — new worktree', () => {autoCreatedAt: expect.any(String),branch: call.branch,isWorktree: true,+ // The send created the branch: the run end may look its PR up.+ ownBranch: call.branch,},path: '/code/lobehub',repoType: 'github',diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.tsindex 831b0d23bf0..d99a822b6bc 100644--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts@@ -175,6 +175,8 @@ const createWorktree = async (result.ownerToken === ownerToken && { ownerNonce: receipt?.nonce, ownerToken }),branch,isWorktree: true,+ // The send created this branch: the run end may look its PR up.+ ownBranch: branch,},path: target.sourcePath,repoType: target.isGithub ? 'github' : 'git',diff --git a/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsxindex aeedbb972d6..881ef34bbba 100644--- a/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx+++ b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx@@ -1,6 +1,7 @@import { DropdownMenu, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { GitPullRequest } from 'lucide-react';+import { GitPullRequest, TriangleAlertIcon } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -32,6 +33,7 @@ interface TopicPullRequestChipProps {*/const TopicPullRequestChip = memo<TopicPullRequestChipProps>(({ deviceId, path, topicId }) => {const { t } = useTranslation('device');+ const { t: tChat } = useTranslation('chat');const { primary, probes, views } = useTopicPullRequests({ deviceId, path, topicId });const extra = views.length - 1;@@ -40,13 +42,23 @@ const TopicPullRequestChip = memo<TopicPullRequestChipProps>(({ deviceId, path,views.map((view) => {const visual = PR_STATE_VISUAL[getPullRequestState(view)];return {+ // How the PR was linked is kept, not shown; only a PR the app cannot+ // vouch for is flagged, since its merge / close stay locked.+ extra: view.vouched ? undefined : (+ <Icon+ aria-label={tChat('workingPanel.overview.pr.unvouched')}+ color={cssVar.colorWarning}+ icon={TriangleAlertIcon}+ size={12}+ />+ ),icon: <Icon color={visual.color} icon={visual.icon} size={14} />,key: view.identifier,label: `#${view.number} ${view.title}`,onClick: () => openTrustedExternalUrl(view.url),};}),- [views],+ [tChat, views],);const probeReads = <TopicPullRequestProbes deviceId={deviceId} path={path} probes={probes} />;diff --git a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsx b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsxnew file mode 100644index 00000000000..05ab105c5e2--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsx@@ -0,0 +1,75 @@+'use client';++import { Button, createModal, Flexbox, Input, useModalContext } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { t } from 'i18next';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useLinkPullRequestField } from './useLinkPullRequestField';++const styles = stylex.create({+ error: { fontSize: '12px', color: cssVar.colorError },+});++interface LinkPullRequestContentProps {+ /** Resolves to the linked `owner/repo#n`. */+ onLink: (url: string) => Promise<string | undefined>;+}++const LinkPullRequestContent = memo<LinkPullRequestContentProps>(({ onLink }) => {+ const { t: tChat } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ const field = useLinkPullRequestField(onLink, close);++ return (+ <Flexbox gap={16}>+ <Flexbox gap={6}>+ <Input+ autoFocus+ aria-invalid={field.invalid || undefined}+ aria-label={tChat('workingPanel.overview.pr.link')}+ disabled={field.linking}+ placeholder={tChat('workingPanel.overview.pr.linkPlaceholder')}+ value={field.value}+ onChange={(event) => field.change(event.target.value)}+ onPressEnter={() => void field.submit()}+ />+ {field.invalid && (+ <div role={'alert'} {...stylex.props(styles.error)}>+ {tChat('workingPanel.overview.pr.linkInvalid')}+ </div>+ )}+ </Flexbox>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={field.linking} onClick={close}>+ {tCommon('cancel')}+ </Button>+ <Button+ disabled={!field.value.trim()}+ loading={field.linking}+ type={'primary'}+ onClick={() => void field.submit()}+ >+ {tChat('workingPanel.overview.pr.linkAction')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++LinkPullRequestContent.displayName = 'LinkPullRequestContent';++/**+ * Better Coding Experience: link a PR the agent's commands never touched by+ * pasting its GitHub URL.+ */+export const openLinkPullRequestModal = (onLink: LinkPullRequestContentProps['onLink']) =>+ createModal({+ content: <LinkPullRequestContent onLink={onLink} />,+ footer: null,+ title: t('workingPanel.overview.pr.link', { ns: 'chat' }),+ width: 440,+ });diff --git a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsxnew file mode 100644index 00000000000..ada799bd51f--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsx@@ -0,0 +1,28 @@+import { LinkIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { openLinkPullRequestModal } from './LinkPullRequestModal';+import { OverviewRow } from './OverviewRow';++interface LinkPullRequestRowProps {+ /** Resolves to the linked `owner/repo#n`. */+ onLink: (url: string) => Promise<string | undefined>;+}++/** Better Coding Experience: the repository card's "Link a pull request" action. */+export const LinkPullRequestRow = memo<LinkPullRequestRowProps>(({ onLink }) => {+ const { t } = useTranslation('chat');++ return (+ <OverviewRow+ weak+ icon={LinkIcon}+ iconSize={14}+ value={t('workingPanel.overview.pr.link')}+ onClick={() => openLinkPullRequestModal(onLink)}+ />+ );+});++LinkPullRequestRow.displayName = 'OverviewLinkPullRequestRow';diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsxindex 279547cc611..6495fb55509 100644--- a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx@@ -1,5 +1,7 @@import type { DeviceGitLinkedPullRequest } from '@lobechat/types';-import { Icon, Tooltip } from '@lobehub/ui';+import { ActionIcon, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { TriangleAlertIcon, XIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -15,49 +17,79 @@ import { sectionStyles } from './sectionStyles';interface PullRequestRowProps {onClick: () => void;+ /** Better Coding Experience: remove the PR from the topic's lists. */+ onDismiss?: () => void;pullRequest: DeviceGitLinkedPullRequest;/** Defaults to `#number title`. */tooltip?: string;+ /** The app cannot vouch the PR belongs to the topic (its merge / close are locked). */+ unvouched?: boolean;}/** 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)];+const PullRequestRow = memo<PullRequestRowProps>(+ ({ onClick, onDismiss, pullRequest, tooltip, unvouched }) => {+ 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>- );-});+ return (+ <Tooltip title={tooltip ?? `#${pullRequest.number} ${pullRequest.title}`}>+ <div>+ <OverviewRow+ icon={prVisual.icon}+ iconColor={prVisual.color}+ trailing={+ <>+ {unvouched && (+ <Tooltip title={t('workingPanel.overview.pr.unvouched')}>+ <Icon+ aria-label={t('workingPanel.overview.pr.unvouched')}+ color={cssVar.colorWarning}+ icon={TriangleAlertIcon}+ size={13}+ />+ </Tooltip>+ )}+ <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>+ {onDismiss && (+ <ActionIcon+ aria-label={t('workingPanel.overview.pr.dismiss')}+ icon={XIcon}+ size={'small'}+ title={t('workingPanel.overview.pr.dismiss')}+ onClick={(event) => {+ event.stopPropagation();+ onDismiss();+ }}+ />+ )}+ </>+ }+ value={+ <>+ <span className={rowStyles.num}>#{pullRequest.number}</span>+ {pullRequest.title}+ </>+ }+ onClick={onClick}+ />+ </div>+ </Tooltip>+ );+ },+);PullRequestRow.displayName = 'OverviewPullRequestRow';diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 36d18d11f0d..b9e9e550a70 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -57,6 +57,7 @@ import { toLinkedPullRequest } from '../PullRequest/useSidebarPullRequests';import { BackgroundTasksSection } from './BackgroundTasks';import DeviceStatusSection from './DeviceStatusSection';import KeptWorktreeRows, { RemovedWorktreeRow, useTopicWorktrees } from './KeptWorktreeRows';+import { LinkPullRequestRow } from './LinkPullRequestRow';import {collectChangeStats,isLinkedWorktreeCheckout,@@ -85,6 +86,10 @@ interface OverviewProps {/** Routes file / git RPCs; empty for "This device", which reads over IPC. */deviceId?: string;environmentAvailable: boolean;+ /** Better Coding Experience: remove one of {@link pullRequests} from the topic. */+ onDismissPullRequest?: (pullRequest: TopicPullRequestView) => Promise<void>;+ /** Better Coding Experience: link a PR by URL; resolves to its `owner/repo#n`. */+ onLinkPullRequest?: (url: string) => Promise<string | undefined>;/** Better Coding Experience: open one of {@link pullRequests}. */onOpenPullRequest?: (pullRequest: TopicPullRequestView) => void;onOpenTab: (tab: string) => void;@@ -111,6 +116,8 @@ const Overview = memo<OverviewProps>(agentId,deviceId,environmentAvailable,+ onDismissPullRequest,+ onLinkPullRequest,onOpenPullRequest,onOpenTab,onRefreshPullRequest,@@ -294,16 +301,36 @@ 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) => (+ const pullRequestRows = pullRequests ? (+ <>+ {pullRequests.map((view) => (<PullRequestRowkey={view.identifier}pullRequest={toLinkedPullRequest(view)}tooltip={`${view.repoFullName}#${view.number} ${view.title}`}+ unvouched={!view.vouched}onClick={() => onOpenPullRequest?.(view)}+ onDismiss={+ onDismissPullRequest &&+ (() =>+ void onDismissPullRequest(view).then(+ () =>+ toast.info(+ t('workingPanel.overview.pr.dismissed', { name: `#${view.number}` }),+ ),+ () =>+ toast.error(+ t('workingPanel.overview.pr.dismissFailed', { name: `#${view.number}` }),+ ),+ ))+ }/>- ))- : pullRequest && <PullRequestRow pullRequest={pullRequest} onClick={() => onOpenTab('pr')} />;+ ))}+ {onLinkPullRequest && <LinkPullRequestRow onLink={onLinkPullRequest} />}+ </>+ ) : (+ pullRequest && <PullRequestRow pullRequest={pullRequest} onClick={() => onOpenTab('pr')} />+ );const gitRows = (<>diff --git a/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.test.ts b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.test.tsnew file mode 100644index 00000000000..0db8d5b61c4--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.test.ts@@ -0,0 +1,82 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { isPullRequestUrl, useLinkPullRequestField } from './useLinkPullRequestField';++const toastMocks = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, unknown>) =>+ values ? `${key}:${JSON.stringify(values)}` : key,+ }),+}));+vi.mock('@lobehub/ui', () => ({ toast: toastMocks }));++describe('isPullRequestUrl', () => {+ it('accepts a github.com PR page, also a tab of it', () => {+ expect(isPullRequestUrl(' https://github.com/a/b/pull/1 ')).toBe(true);+ expect(isPullRequestUrl('https://github.com/a/b/pull/1/files?w=1')).toBe(true);+ });++ it('rejects anything else', () => {+ expect(isPullRequestUrl('https://github.com/a/b/issues/1')).toBe(false);+ expect(isPullRequestUrl('https://gitlab.com/a/b/pull/1')).toBe(false);+ expect(isPullRequestUrl('a/b#1')).toBe(false);+ });+});++describe('useLinkPullRequestField', () => {+ beforeEach(() => vi.clearAllMocks());++ const setup = (onLink = vi.fn(async () => 'a/b#1')) => {+ const onDone = vi.fn();+ const hook = renderHook(() => useLinkPullRequestField(onLink, onDone));+ return { hook, onDone, onLink };+ };++ it('links a pasted PR URL, confirms it, and closes the dialog', async () => {+ const { hook, onDone, onLink } = setup();++ act(() => hook.result.current.change(' https://github.com/a/b/pull/1 '));+ await act(() => hook.result.current.submit());++ expect(onLink).toHaveBeenCalledWith('https://github.com/a/b/pull/1');+ expect(toastMocks.success).toHaveBeenCalledWith(+ 'workingPanel.overview.pr.linked:{"name":"a/b#1"}',+ );+ expect(onDone).toHaveBeenCalledTimes(1);+ });++ it('explains a URL that is not a PR without asking the server', async () => {+ const { hook, onDone, onLink } = setup();++ act(() => hook.result.current.change('https://github.com/a/b/issues/1'));+ await act(() => hook.result.current.submit());++ expect(hook.result.current.invalid).toBe(true);+ expect(onLink).not.toHaveBeenCalled();+ expect(onDone).not.toHaveBeenCalled();+ // Typing again clears the explanation.+ act(() => hook.result.current.change('https://github.com/a/b/pull/2'));+ expect(hook.result.current.invalid).toBe(false);+ });++ it('reports a failed link and keeps the dialog open', async () => {+ const { hook, onDone } = setup(+ vi.fn(async () => {+ throw new Error('nope');+ }),+ );++ act(() => hook.result.current.change('https://github.com/a/b/pull/1'));+ await act(() => hook.result.current.submit());++ expect(toastMocks.error).toHaveBeenCalledWith('workingPanel.overview.pr.linkFailed');+ expect(onDone).not.toHaveBeenCalled();+ expect(hook.result.current.linking).toBe(false);+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.ts b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.tsnew file mode 100644index 00000000000..d53b70241da--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.ts@@ -0,0 +1,49 @@+import { toast } from '@lobehub/ui';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++/** `https://github.com/<owner>/<repo>/pull/<n>`, also with a tab or query after it. */+const PULL_URL_RE = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+(?:[/?#]\S*)?$/i;++export const isPullRequestUrl = (value: string) => PULL_URL_RE.test(value.trim());++/**+ * State of the "Link a pull request" dialog's field: links on submit, explains+ * a URL that is not a PR without asking the server, and calls `onDone` once+ * linked (the dialog closes then). A failed link keeps the field for a retry.+ */+export const useLinkPullRequestField = (+ onLink: (url: string) => Promise<string | undefined>,+ onDone: () => void,+) => {+ const { t } = useTranslation('chat');+ const [value, setValue] = useState('');+ const [linking, setLinking] = useState(false);+ const [invalid, setInvalid] = useState(false);++ const change = useCallback((next: string) => {+ setValue(next);+ setInvalid(false);+ }, []);++ const submit = useCallback(async () => {+ if (linking) return;+ const url = value.trim();+ if (!isPullRequestUrl(url)) {+ setInvalid(true);+ return;+ }+ setLinking(true);+ try {+ const identifier = await onLink(url);+ toast.success(t('workingPanel.overview.pr.linked', { name: identifier ?? url }));+ onDone();+ } catch {+ toast.error(t('workingPanel.overview.pr.linkFailed'));+ } finally {+ setLinking(false);+ }+ }, [linking, onDone, onLink, t, value]);++ return { change, invalid, linking, submit, value };+};diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.tsindex e96eb055037..5a10d827083 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts@@ -15,6 +15,8 @@ const mocks = vi.hoisted(() => ({probes: [] as any[],views: [] as any[],},+ dismiss: vi.fn(async () => ({ updated: true })),+ link: vi.fn(async () => ({ identifier: 'a/b#4', linked: true })),refresh: vi.fn(),}));@@ -27,7 +29,13 @@ vi.mock('@/store/user/selectors', () => ({vi.mock('@/features/TopicPullRequests/useTopicPullRequests', () => ({useTopicPullRequests: () => mocks.linked,}));-vi.mock('@/services/work', () => ({ workService: { refreshTopicPullRequests: mocks.refresh } }));+vi.mock('@/services/work', () => ({+ workService: {+ linkTopicPullRequest: mocks.link,+ refreshTopicPullRequests: mocks.refresh,+ setTopicPullRequestDismissed: mocks.dismiss,+ },+}));vi.mock('../useLinkedPullRequest', () => ({useLinkedPullRequest: (params: unknown) => {mocks.legacy(params);@@ -40,6 +48,8 @@ const view = (number: number, extra: Record<string, unknown> = {}) => ({identifier: `a/b#${number}`,isDraft: false,localDetail: true,+ source: 'created',+ vouched: true,number,repoFullName: 'a/b',state: 'open',@@ -108,4 +118,62 @@ describe('useSidebarPullRequests', () => {result.current.onRetryConfirm?.();expect(mocks.refresh).toHaveBeenCalledWith('t1');});++ it('keeps a confirmed PR locked when the app cannot vouch for it', () => {+ const views = [view(3, { vouched: false })];+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));++ expect(result.current.confirmed).toBe(false);+ });++ it('removes and links PRs on the topic, then refreshes its list', async () => {+ const views = [view(3)];+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));++ await act(async () => {+ await result.current.dismissPullRequest?.(views[0] as any);+ });+ expect(mocks.dismiss).toHaveBeenCalledWith({+ dismissed: true,+ identifier: 'a/b#3',+ topicId: 't1',+ });++ let identifier: string | undefined;+ await act(async () => {+ identifier = await result.current.linkPullRequest?.('https://github.com/a/b/pull/4');+ });+ expect(mocks.link).toHaveBeenCalledWith({+ source: 'manual',+ topicId: 't1',+ url: 'https://github.com/a/b/pull/4',+ });+ expect(identifier).toBe('a/b#4');+ expect(mocks.refresh).toHaveBeenCalledTimes(2);+ });++ it('rejects a link or removal the server did not save', async () => {+ const views = [view(3)];+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.link.mockResolvedValueOnce({ identifier: 'a/b#4', linked: false });+ mocks.dismiss.mockResolvedValueOnce({ updated: false });+ const { result } = renderHook(() => useSidebarPullRequests(PARAMS));++ await expect(+ result.current.linkPullRequest?.('https://github.com/a/b/pull/4'),+ ).rejects.toThrow();+ await expect(result.current.dismissPullRequest?.(views[0] as any)).rejects.toThrow();+ expect(mocks.refresh).not.toHaveBeenCalled();+ });++ it('offers no link or removal before the conversation has a topic', () => {+ const views = [view(3)];+ mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ const { result } = renderHook(() => useSidebarPullRequests({ ...PARAMS, topicId: null }));++ expect(result.current.linkPullRequest).toBeUndefined();+ expect(result.current.dismissPullRequest).toBeUndefined();+ });});diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.tsindex 5f2a722480d..a6e9af2d575 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts@@ -59,13 +59,56 @@ export const useSidebarPullRequests = (params: {[params.topicId],);+ const topicId = params.topicId;+ const dismissPullRequest = useCallback(+ async (view: TopicPullRequestView) => {+ if (!topicId) return;+ const { updated } = await workService.setTopicPullRequestDismissed({+ dismissed: true,+ identifier: view.identifier,+ topicId,+ });+ // Not saved (lost write race, topic not reachable): the caller reports it.+ if (!updated) throw new Error(`Could not remove ${view.identifier}`);+ await refresh();+ },+ [refresh, topicId],+ );+ /** Link a PR by URL; resolves to its `owner/repo#n`, or throws on a bad URL. */+ const linkPullRequest = useCallback(+ async (url: string) => {+ if (!topicId) return undefined;+ const { identifier, linked } = await workService.linkTopicPullRequest({+ source: 'manual',+ topicId,+ url,+ });+ // Not saved: reject so the dialog stays open with its error.+ if (!linked) throw new Error(`Could not link ${identifier}`);+ await refresh();+ return identifier;+ },+ [refresh, topicId],+ );+if (!linked.enabled) {- return { ...legacy, pickPullRequest: undefined, probes: [], pullRequests: undefined };+ return {+ ...legacy,+ dismissPullRequest: undefined,+ linkPullRequest: undefined,+ pickPullRequest: undefined,+ probes: [],+ pullRequests: undefined,+ };}return {confirmError: undefined,- confirmed: !!selected?.confirmed,+ // Mutations need a confirmed read AND a PR the app can vouch for.+ confirmed: !!selected?.confirmed && !!selected?.vouched,+ // A new conversation has no topic to keep a link on until its first send.+ dismissPullRequest: topicId ? dismissPullRequest : undefined,+ linkPullRequest: topicId ? linkPullRequest : undefined,onRetryConfirm: () => void refresh(),/** Open a listed PR: in the PR tab when the pane can read it, else on GitHub. */pickPullRequest: (view: TopicPullRequestView) => {diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex ce830885566..a49e1adfa50 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -410,6 +410,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })repoType === 'github' || (!repoType && !!snapshotConfig?.git?.github?.pullRequest);const gitPath = filesystemEnvironmentAvailable && isGithub ? workingDirectory : undefined;const {+ dismissPullRequest,+ linkPullRequest,pickPullRequest,probes: pullRequestProbes,pullRequest,@@ -917,6 +919,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })sourcePath={sourceWorkingDirectory}statusDeviceId={getStatusDeviceId(effectiveTarget, agencyConfig?.boundDeviceId)}workingDirectory={environmentWorkingDirectory}+ onDismissPullRequest={dismissPullRequest}+ onLinkPullRequest={linkPullRequest}onOpenTab={openTab}onRefreshPullRequest={refreshPullRequest}onOpenPullRequest={diff --git a/src/features/TopicPullRequests/pullRequestView.test.ts b/src/features/TopicPullRequests/pullRequestView.test.tsindex 435bfffdabe..ef4a34c0231 100644--- a/src/features/TopicPullRequests/pullRequestView.test.ts+++ b/src/features/TopicPullRequests/pullRequestView.test.ts@@ -9,6 +9,7 @@ const item = (number: number, overrides: Record<string, unknown> = {}) =>number,repoFullName: 'lobehub/lobehub',scm: null,+ source: 'created',status: 'open',title: `PR ${number}`,url: `https://github.com/lobehub/lobehub/pull/${number}`,@@ -101,3 +102,23 @@ describe('resolvePullRequestView · localDetail', () => {expect(resolvePullRequestView(item(1, { scm })).localDetail).toBe(false);});});++describe('resolvePullRequestView · trust', () => {+ it('carries how the PR was linked and whether it is vouched', () => {+ expect(resolvePullRequestView(item(4, { source: 'branch', vouched: false }))).toMatchObject({+ source: 'branch',+ vouched: false,+ });+ // A list persisted before these fields existed.+ expect(resolvePullRequestView(item(5, { source: undefined }))).toMatchObject({+ source: 'created',+ vouched: true,+ });+ });+});++describe('resolvePullRequestView · untitled', () => {+ it('names the repository when no title is known yet, not the number again', () => {+ expect(resolvePullRequestView(item(12, { title: null })).title).toBe('lobehub/lobehub');+ });+});diff --git a/src/features/TopicPullRequests/pullRequestView.ts b/src/features/TopicPullRequests/pullRequestView.tsindex bc11a7a5503..c2bdcf952c3 100644--- a/src/features/TopicPullRequests/pullRequestView.ts+++ b/src/features/TopicPullRequests/pullRequestView.ts@@ -3,6 +3,7 @@ import type {DeviceGitPullRequestCiStatus,DeviceGitPullRequestDetail,TopicPullRequestItem,+ TopicPullRequestLinkSource,} from '@lobechat/types';import type { PullRequestState } from '@/features/AgentSidebar/Topic/List/Item/metaCardData';@@ -24,9 +25,13 @@ export interface TopicPullRequestView {mergedAt?: string | null;number: number;repoFullName: string;+ /** How the topic came to it; see {@link TopicPullRequestLinkSource}. */+ source: TopicPullRequestLinkSource;state: PullRequestState;title: string;url: string;+ /** The app can vouch it belongs to the topic; merge / close stay locked otherwise. */+ vouched: boolean;}/** Device detail for a number, with whether this session confirmed it. */@@ -65,7 +70,10 @@ export const resolvePullRequestView = (identifier: item.identifier,number: item.number,repoFullName: item.repoFullName,+ // Persisted lists from before these fields existed read as the strongest kind.+ source: item.source ?? 'created',url: fallbackUrl(item),+ vouched: item.vouched ?? true,};const sameRepo = !!device && isSameRepository(device.detail, item.repoFullName);@@ -79,7 +87,7 @@ export const resolvePullRequestView = (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}`,+ title: item.scm.title ?? item.title ?? item.repoFullName,};}@@ -105,7 +113,9 @@ export const resolvePullRequestView = (isDraft: status === 'draft',localDetail: false,state: status === 'merged' ? 'merged' : status === 'closed' ? 'closed' : 'open',- title: item.title ?? `#${item.number}`,+ // No title known yet (a PR linked by hand before any read): name its repo+ // rather than repeat the number the row already shows.+ title: item.title ?? item.repoFullName,};};diff --git a/src/services/electron/git.ts b/src/services/electron/git.tsindex 938ad5518f8..6f78abdd7af 100644--- a/src/services/electron/git.ts+++ b/src/services/electron/git.ts@@ -51,6 +51,7 @@ class ElectronGitService {branch: string;path: string;pullRequestNumber?: number;+ state?: 'all' | 'open';}): Promise<GitLinkedPullRequestResult> {return this.ipc.git.getLinkedPullRequest(params);}diff --git a/src/services/git.ts b/src/services/git.tsindex ea2cd5cd719..6814826069f 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -83,6 +83,8 @@ export interface GitLinkedPRSummary {ghMissing?: boolean;pullRequest?: DeviceGitLinkedPullRequest | null;pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;+ /** `owner/repo` of the GitHub remote the branch publishes to. */+ remoteRepoFullName?: string;upstream?: DeviceGitUpstreamRef;}@@ -302,11 +304,14 @@ class GitService {deviceId,path,pullRequestNumber,+ state,}: {branch: string;deviceId?: string;path: string;pullRequestNumber?: number;+ /** `open`: discovery of a branch's open PR; default lists every state. */+ state?: 'all' | 'open';}): Promise<GitLinkedPRSummary | undefined> {const pr = deviceId? await lambdaClient.device.gitLinkedPullRequest.query({@@ -314,14 +319,21 @@ class GitService {deviceId,path,pullRequestNumber,+ ...(state ? { state } : {}),})- : await electronGitService.getLinkedPullRequest({ branch, path, pullRequestNumber });+ : await electronGitService.getLinkedPullRequest({+ branch,+ path,+ pullRequestNumber,+ ...(state ? { state } : {}),+ });if (!pr) return undefined;return {extraCount: pr.extraCount,ghMissing: pr.status === 'gh-missing',pullRequest: pr.pullRequest,pullRequestStatus: pr.status,+ remoteRepoFullName: pr.remoteRepoFullName,upstream: pr.upstream,};}diff --git a/src/services/work.ts b/src/services/work.tsindex b753935d7f7..74e76f68e61 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -143,6 +143,7 @@ class WorkService {linkPushedPullRequests = async (params: {pullRequests: {headRefName: string;+ headRepoFullName?: string;isDraft?: boolean;number: number;state?: string;@@ -153,6 +154,29 @@ class WorkService {topicId: string;}) => lambdaClient.work.linkPushedPullRequests.mutate(params);+ /**+ * Better Coding Experience: keep a PR on the topic itself — found on its own+ * branch (`branch`) or linked by hand (`manual`). Display-only links: they+ * never feed the SCM links that accept deliveries or wake agents.+ */+ linkTopicPullRequest = async (params: {+ headRefName?: string;+ source: 'branch' | 'manual';+ title?: string;+ topicId: string;+ url: string;+ vouched?: boolean;+ }): Promise<{ identifier: string; linked: boolean }> =>+ lambdaClient.work.linkTopicPullRequest.mutate(params);++ /** Better Coding Experience: remove a PR from the topic's lists, or bring it back. */+ setTopicPullRequestDismissed = async (params: {+ dismissed: boolean;+ identifier: string;+ topicId: string;+ }): Promise<{ updated: boolean }> =>+ lambdaClient.work.setTopicPullRequestDismissed.mutate(params);+/** Revalidate a topic's linked pull requests (mounted reads only). */refreshTopicPullRequests = async (topicId?: string | null) => {if (!topicId) return;diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.tsnew file mode 100644index 00000000000..a8122557f04--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.ts@@ -0,0 +1,102 @@+import type { ConversationContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ChatStore } from '@/store/chat/store';++import { messageMapKey } from '../../../../utils/messageMapKey';+import { buildRunLifecycle } from './buildRunLifecycle';++const mocks = vi.hoisted(() => ({+ betterCoding: true,+ linkOwnBranchPullRequest: vi.fn(async () => {}),+ refreshTopicPullRequests: vi.fn(async () => {}),+}));++vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest', () => ({+ linkOwnBranchPullRequest: mocks.linkOwnBranchPullRequest,+}));+vi.mock('@/services/work', () => ({+ workService: { refreshTopicPullRequests: mocks.refreshTopicPullRequests },+}));+// Partial: the queued follow-up path reads other user selectors (follow-up mode).+vi.mock('@/store/user/selectors', async (importOriginal) => {+ const actual = await importOriginal<any>();+ return {+ ...actual,+ labPreferSelectors: {+ ...actual.labPreferSelectors,+ enableBetterCodingExperience: () => mocks.betterCoding,+ },+ };+});+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));++const OP = 'op1';+const CONTEXT = { agentId: 'a1', topicId: 't1' } as ConversationContext;++const makeStore = (queued: boolean) => {+ const store = {+ activeAgentId: 'a1',+ activeTopicId: 't1',+ completeOperation: vi.fn(),+ dbMessagesMap: {},+ drainQueuedMessages: vi.fn(() => (queued ? [{ content: 'next', id: 'q1' }] : [])),+ failOperation: vi.fn(),+ markTopicUnread: vi.fn(),+ messagesMap: {},+ operations: { [OP]: { context: CONTEXT, id: OP, metadata: {}, status: 'running' } },+ operationsByContext: { [messageMapKey(CONTEXT)]: [OP] },+ queuedMessages: queued ? { [messageMapKey(CONTEXT)]: [{ content: 'next', id: 'q1' }] } : {},+ sendMessage: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {},+ updateOperationMetadata: vi.fn(),+ updateTopicStatus: vi.fn(async () => {}),+ };+ return (() => store) as unknown as () => ChatStore;+};++const complete = (get: () => ChatStore, runtimeStatus: 'done' | 'error' = 'done') =>+ buildRunLifecycle(get, {+ context: CONTEXT,+ parentMessageId: 'u1',+ parentMessageType: 'user',+ runId: OP,+ runScope: 'top_level',+ runtimeType: 'client',+ }).completeRun({+ context: CONTEXT,+ operationId: OP,+ runId: OP,+ runScope: 'top_level',+ runtimeStatus,+ runtimeType: 'client',+ });++describe('buildRunLifecycle.completeRun — topic pull requests', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.betterCoding = true;+ });++ it('looks up the own-branch PR even when a queued follow-up takes over', async () => {+ const { requeued } = await complete(makeStore(true));++ expect(requeued).toBe(true);+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledWith('t1');+ expect(mocks.linkOwnBranchPullRequest).toHaveBeenCalledWith(expect.any(Function), {+ agentId: 'a1',+ topicId: 't1',+ });+ });++ it('skips the lookup for a failed run and while the lab is off', async () => {+ await complete(makeStore(false), 'error');+ mocks.betterCoding = false;+ await complete(makeStore(false));++ expect(mocks.linkOwnBranchPullRequest).not.toHaveBeenCalled();+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex 9a49b125732..1e05a859b21 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -8,6 +8,7 @@ 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 { linkOwnBranchPullRequest } from '@/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest';import { snapshotTopicWorkingDirGit } from '@/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit';import type { ChatStore } from '@/store/chat/store';import {@@ -18,6 +19,8 @@ import {hasCompletedAssistantText,isAudioOnlyFirstUserMessage,} from '@/store/chat/utils/topicTitle';+import { getUserStoreState } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { toTitleText } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../../utils/messageMapKey';@@ -308,11 +311,6 @@ 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) {@@ -403,6 +401,23 @@ export const buildRunLifecycle = (// cannot strand an audio-first topic without a title.if (disposition === 'success') summarizeVoiceTopicTitleAfterCompletion();+ // Same for the topic's linked PRs: a queued follow-up skips the+ // completion notification, not these. The run's gh / push commands were+ // linked by the completion Work scan before the run reported its end; only+ // a mounted list (Better Coding Experience PR chip / sidebar) refetches.+ if (adapter.runScope !== 'sub_agent') {+ void workService.refreshTopicPullRequests(topicId).catch(() => {});+ // A PR someone opened on the topic's own branch — looked up before a+ // queued turn can move the topic off that branch.+ if (+ disposition === 'success' &&+ topicId &&+ agentId &&+ labPreferSelectors.enableBetterCodingExperience(getUserStoreState())+ )+ void linkOwnBranchPullRequest(get, { agentId, topicId });+ }+const completeSuccess = () => {get().completeOperation(operationId);const completedOp = get().operations[operationId];diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.test.tsnew file mode 100644index 00000000000..78cd1f8d3b3--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.test.ts@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { linkOwnBranchPullRequest } from './linkOwnBranchPullRequest';++const mocks = vi.hoisted(() => ({+ getLinkedPullRequest: vi.fn(),+ linkTopicPullRequest: vi.fn(),+ refreshTopicPullRequests: vi.fn(),+ resolveTopicGitTransport: vi.fn((_agentId: string, _topicDeviceId?: string) => ({+ deviceId: 'dev-1',+ })),+ topic: undefined as any,+}));++vi.mock('@/services/git', () => ({+ gitService: { getLinkedPullRequest: mocks.getLinkedPullRequest },+}));+vi.mock('@/services/work', () => ({+ workService: {+ linkTopicPullRequest: mocks.linkTopicPullRequest,+ refreshTopicPullRequests: mocks.refreshTopicPullRequests,+ },+}));+vi.mock('@/store/chat/utils/topicWorkingDirGit', () => ({+ canReadTopicGitTransport: () => true,+ resolveTopicGitTransport: mocks.resolveTopicGitTransport,+}));+vi.mock('../../../topic/selectors', () => ({+ topicSelectors: { getTopicById: () => () => mocks.topic },+}));++const get = () => ({}) as any;+const run = () => linkOwnBranchPullRequest(get, { agentId: 'a1', topicId: 't1' });++const topicOn = (git: Record<string, unknown>) => ({+ metadata: {+ workingDirectoryConfig: {+ git: { activeWorktree: '/wt', isWorktree: true, ...git },+ path: '/repo',+ },+ },+});++const lookup = (overrides: Record<string, unknown> = {}) => ({+ pullRequest: {+ headRefName: 'lobehub/feat-x',+ headRepoFullName: 'lobehub/lobehub',+ number: 7,+ state: 'OPEN',+ title: 'Opened on GitHub',+ url: 'https://github.com/lobehub/lobehub/pull/7',+ ...overrides,+ },+ pullRequestStatus: 'ok',+ remoteRepoFullName: 'lobehub/lobehub',+ upstream: { branch: 'lobehub/feat-x', remote: 'origin' },+});++const OWN = {+ branch: 'lobehub/feat-x',+ ownBranch: 'lobehub/feat-x',+ upstream: { branch: 'lobehub/feat-x', remote: 'origin' },+};++describe('linkOwnBranchPullRequest', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.linkTopicPullRequest.mockResolvedValue({ identifier: 'lobehub/lobehub#7', linked: true });+ });++ it("links the open PR of the topic's own pushed branch, vouched by its head repo", async () => {+ mocks.topic = topicOn(OWN);+ mocks.getLinkedPullRequest.mockResolvedValue(lookup());++ await run();++ // Open PRs only: an all-state list may put a newer closed PR first.+ expect(mocks.getLinkedPullRequest).toHaveBeenCalledWith({+ branch: 'lobehub/feat-x',+ deviceId: 'dev-1',+ path: '/wt',+ state: 'open',+ });+ expect(mocks.linkTopicPullRequest).toHaveBeenCalledWith({+ headRefName: 'lobehub/feat-x',+ source: 'branch',+ title: 'Opened on GitHub',+ topicId: 't1',+ url: 'https://github.com/lobehub/lobehub/pull/7',+ vouched: true,+ });+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledWith('t1');+ });++ it('leaves a same-named branch in another fork unvouched', async () => {+ mocks.topic = topicOn(OWN);+ mocks.getLinkedPullRequest.mockResolvedValue(lookup({ headRepoFullName: 'stranger/lobehub' }));++ await run();++ expect(mocks.linkTopicPullRequest).toHaveBeenCalledWith(+ expect.objectContaining({ vouched: false }),+ );+ });++ it('never looks up a branch the topic did not create, nor an unpushed one', async () => {+ mocks.topic = topicOn({ ...OWN, ownBranch: undefined });+ await run();+ mocks.topic = topicOn({ ...OWN, branch: 'main' });+ await run();+ mocks.topic = topicOn({ ...OWN, upstream: undefined });+ await run();++ expect(mocks.getLinkedPullRequest).not.toHaveBeenCalled();+ });++ it('ignores a merged or closed PR on the branch', async () => {+ mocks.topic = topicOn(OWN);+ mocks.getLinkedPullRequest.mockResolvedValue(lookup({ state: 'MERGED' }));++ await run();++ expect(mocks.linkTopicPullRequest).not.toHaveBeenCalled();+ });++ it("routes the lookup through the topic's bound device", async () => {+ mocks.topic = { metadata: { ...topicOn(OWN).metadata, boundDeviceId: 'dev-topic' } };+ mocks.getLinkedPullRequest.mockResolvedValue(lookup());++ await run();++ expect(mocks.resolveTopicGitTransport).toHaveBeenCalledWith('a1', 'dev-topic');+ });+});diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.ts b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.tsnew file mode 100644index 00000000000..39c13b2c75b--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.ts@@ -0,0 +1,68 @@+import { getWorkingDirEffectivePath } from '@lobechat/types';++import { gitService } from '@/services/git';+import { workService } from '@/services/work';+import type { ChatStore } from '@/store/chat/store';+import {+ canReadTopicGitTransport,+ resolveTopicGitTransport,+} from '@/store/chat/utils/topicWorkingDirGit';++import { topicSelectors } from '../../../topic/selectors';++const sameRepo = (a?: string, b?: string) => !!a && !!b && a.toLowerCase() === b.toLowerCase();++/**+ * At the end of a run (Better Coding Experience), link the open PR of the+ * branch the topic CREATED — its first-send worktree branch, or one its agent+ * made — when someone opened it outside the agent's commands (on GitHub, from+ * another tool). Never for a branch the topic merely switched to: that is the+ * branch guess the lab removed, and it may carry someone else's PR.+ *+ * The device answers `gh pr list --head <remote ref>`. The link is a topic+ * link (`source: 'branch'`), vouched only when the PR's head lives in the+ * repository the topic pushes to — a same-named branch in a stranger's fork is+ * listed but stays locked. Best-effort; never throws.+ */+export const linkOwnBranchPullRequest = async (+ get: () => ChatStore,+ { agentId, topicId }: { agentId: string; topicId: string },+): Promise<void> => {+ try {+ const topic = topicSelectors.getTopicById(topicId)(get());+ const config = topic?.metadata?.workingDirectoryConfig;+ const git = config?.git;+ if (!git?.ownBranch || git.detached || git.branch !== git.ownBranch) return;+ // Unpushed: GitHub cannot have a PR for it yet, and asking `gh` is not free.+ if (!git.upstream) return;++ const path = getWorkingDirEffectivePath(config);+ if (!path) return;+ // The device the topic is bound to, where its runs (and this worktree) live.+ const { deviceId } = resolveTopicGitTransport(agentId, topic?.metadata?.boundDeviceId);+ if (!canReadTopicGitTransport({ deviceId })) return;++ // Open PRs only: an all-state list returns the newest first, which may be a+ // closed / merged PR hiding the open one this lookup is for.+ const lookup = await gitService.getLinkedPullRequest({+ branch: git.ownBranch,+ deviceId,+ path,+ state: 'open',+ });+ const pr = lookup?.pullRequestStatus === 'ok' ? lookup.pullRequest : null;+ if (!pr || pr.state.toLowerCase() !== 'open') return;++ const { linked } = await workService.linkTopicPullRequest({+ headRefName: pr.headRefName ?? lookup?.upstream?.branch,+ source: 'branch',+ title: pr.title,+ topicId,+ url: pr.url,+ vouched: sameRepo(pr.headRepoFullName, lookup?.remoteRepoFullName),+ });+ if (linked) await workService.refreshTopicPullRequests(topicId);+ } catch (error) {+ console.error('[linkOwnBranchPullRequest] failed:', error);+ }+};diff --git a/src/store/chat/utils/topicWorkingDirGit.transport.test.ts b/src/store/chat/utils/topicWorkingDirGit.transport.test.tsnew file mode 100644index 00000000000..5d36461215c--- /dev/null+++ b/src/store/chat/utils/topicWorkingDirGit.transport.test.ts@@ -0,0 +1,55 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveTopicGitTransport } from './topicWorkingDirGit';++const env = vi.hoisted(() => ({+ agency: undefined as Record<string, unknown> | undefined,+ currentDeviceId: 'dev-here' as string | undefined,+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<any>()),+ isDesktop: true,+}));+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));+vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => () => env.agency,+ getAgentModelById: () => () => 'gpt-5',+ },+}));+vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({+ gatewayDeviceInfo: env.currentDeviceId ? { deviceId: env.currentDeviceId } : undefined,+ }),+}));++describe('resolveTopicGitTransport', () => {+ beforeEach(() => {+ env.agency = { boundDeviceId: 'dev-b', executionTarget: 'device' };+ env.currentDeviceId = 'dev-here';+ });++ it("follows the agent's target without a topic binding", () => {+ expect(resolveTopicGitTransport('a1')).toMatchObject({ deviceId: 'dev-b' });+ });++ it("keeps a topic on its bound device after the agent's default moved", () => {+ expect(resolveTopicGitTransport('a1', 'dev-a')).toMatchObject({+ deviceId: 'dev-a',+ targetDeviceId: 'dev-a',+ });+ });++ it('reads this machine over IPC when the topic is bound to it', () => {+ expect(resolveTopicGitTransport('a1', 'dev-here')).toMatchObject({+ deviceId: undefined,+ isLocalDevice: true,+ });+ });++ it('lets a fixed selection policy win over the topic binding, as runs do', () => {+ env.agency = { ...env.agency, executionTargetSelectionPolicy: 'fixed' };+ expect(resolveTopicGitTransport('a1', 'dev-a')).toMatchObject({ deviceId: 'dev-b' });+ });+});diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.tsindex 6ec8e0461ae..ab49118f523 100644--- a/src/store/chat/utils/topicWorkingDirGit.ts+++ b/src/store/chat/utils/topicWorkingDirGit.ts@@ -1,4 +1,4 @@-import { isDesktop } from '@lobechat/const';+import { isDesktop, isHeterogeneousAgentModelId } from '@lobechat/const';import type {ChatTopicMetadata,DeviceGitUpstreamRef,@@ -8,6 +8,7 @@ import type {import { dropStaleAutoCreated, getWorkingDirEffectivePath } from '@lobechat/types';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';+import { applyTopicDeviceBinding } from '@/helpers/executionTarget';import type { GitLinkedPRSummary } from '@/services/git';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -29,10 +30,31 @@ export interface TopicLinkedPullRequestBase {export const canReadTopicGitTransport = (transport: Pick<TopicGitTransport, 'deviceId'>) =>!!transport.deviceId || isDesktop;-export const resolveTopicGitTransport = (agentId: string): TopicGitTransport => {+/**+ * Where the topic's git reads go: the agent's execution target — or, when the+ * topic is bound to a device (`topicDeviceId`), that device, by the same rules+ * the run applies (`applyTopicDeviceBinding`): a run keeps executing on the+ * topic's device after the agent's default moves elsewhere.+ */+export const resolveTopicGitTransport = (+ agentId: string,+ topicDeviceId?: string,+): TopicGitTransport => {const agentState = getAgentStoreState();- const agencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(agentState);const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;+ const agentAgencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(agentState);+ const agencyConfig = topicDeviceId+ ? applyTopicDeviceBinding(+ { agencyConfig: agentAgencyConfig, workspaceScoped: false },+ topicDeviceId,+ currentDeviceId,+ {+ isHetero: isHeterogeneousAgentModelId(+ agentByIdSelectors.getAgentModelById(agentId)(agentState),+ ),+ },+ ).agencyConfig+ : agentAgencyConfig;const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;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.tsindex 6a32982d073..dc7309ad0eb 100644--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts@@ -139,4 +139,80 @@ describe('recordGitCommandEffects — Better Coding Experience', () => {expect.objectContaining({ branch: 'feat/x', toolCallId: 'call-push' }),);});++ it("records a branch the agent created as the topic's own", async () => {+ await recordGitCommandEffects({+ command: 'git switch -c feat/new',+ resultContent: "Switched to a new branch 'feat/new'",+ toolCallId: 'call-1',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git).toMatchObject(+ { branch: 'feat/new', ownBranch: 'feat/new' },+ );+ });++ it('does not own a branch it only switched to', async () => {+ await recordGitCommandEffects({+ command: 'git switch main',+ resultContent: "Switched to branch 'main'",+ toolCallId: 'call-1',+ topicId: 't1',+ });++ expect(+ chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git,+ ).not.toHaveProperty('ownBranch');+ });++ it('owns a branch created by a quiet switch that printed nothing', async () => {+ await recordGitCommandEffects({+ command: 'git switch -q -c feat/quiet',+ resultContent: '',+ toolCallId: 'call-1',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git).toMatchObject(+ { branch: 'feat/quiet', ownBranch: 'feat/quiet' },+ );+ });++ it('owns a branch only when the flag guarantees creation, not a create-or-reset', async () => {+ for (const command of [+ 'git switch -q -C feat/x feat/x',+ 'git checkout -q -B feat/x',+ 'git worktree add -B feat/x /tmp/wt',+ ]) {+ chatMocks.updateTopicMetadata.mockClear();+ chatMocks.topics = { t1: topic() };+ await recordGitCommandEffects({ command, resultContent: '', toolCallId: 'c', topicId: 't1' });+ const git = chatMocks.updateTopicMetadata.mock.calls[0]?.[1].workingDirectoryConfig.git;+ expect(git?.ownBranch).toBeUndefined();+ }++ chatMocks.updateTopicMetadata.mockClear();+ await recordGitCommandEffects({+ command: 'git checkout -q -b feat/new',+ resultContent: '',+ toolCallId: 'c',+ topicId: 't1',+ });+ expect(+ chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git.ownBranch,+ ).toBe('feat/new');+ });++ it('does not own a branch whose creation a fallback may have rescued', async () => {+ await recordGitCommandEffects({+ command: 'git switch -q -c feat/x || git switch -q feat/x',+ resultContent: '',+ toolCallId: 'c',+ topicId: 't1',+ });++ const git = chatMocks.updateTopicMetadata.mock.calls[0]?.[1].workingDirectoryConfig.git;+ expect(git?.ownBranch).toBeUndefined();+ });});diff --git a/src/store/tool/slices/builtin/executors/ownBranch.test.ts b/src/store/tool/slices/builtin/executors/ownBranch.test.tsnew file mode 100644index 00000000000..7c443ebab53--- /dev/null+++ b/src/store/tool/slices/builtin/executors/ownBranch.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { applyOwnBranchToConfig, parseCreatedBranch } from './ownBranch';++describe('parseCreatedBranch', () => {+ it.each([+ ["Switched to a new branch 'feat/x'", 'feat/x'],+ ["Preparing worktree (new branch 'lobehub/feat-y')\nHEAD is now at abc", 'lobehub/feat-y'],+ [+ 'Created worktree at /tmp/wt on branch worktree-v1.2. The session is now working in the worktree',+ 'worktree-v1.2',+ ],+ ])('reads a created branch from %s', (content, branch) => {+ expect(parseCreatedBranch(content)).toBe(branch);+ });++ it('ignores a switch to an existing branch', () => {+ expect(parseCreatedBranch("Switched to branch 'main'")).toBeUndefined();+ expect(parseCreatedBranch("Preparing worktree (checking out 'main')")).toBeUndefined();+ expect(+ parseCreatedBranch('Entered worktree at /tmp/wt on branch main. The session'),+ ).toBeUndefined();+ expect(parseCreatedBranch(undefined)).toBeUndefined();+ });+});++describe('applyOwnBranchToConfig', () => {+ const config = { git: { branch: 'feat/x' }, path: '/repo' };++ it('records the created branch only while the topic is on it', () => {+ expect(applyOwnBranchToConfig(config, 'feat/x')?.git?.ownBranch).toBe('feat/x');+ expect(applyOwnBranchToConfig(config, 'feat/other')).toBe(config);+ expect(applyOwnBranchToConfig(config, undefined)).toBe(config);+ });+});diff --git a/src/store/tool/slices/builtin/executors/ownBranch.ts b/src/store/tool/slices/builtin/executors/ownBranch.tsnew file mode 100644index 00000000000..57b0ee7444e--- /dev/null+++ b/src/store/tool/slices/builtin/executors/ownBranch.ts@@ -0,0 +1,40 @@+import type { WorkingDirConfig } from '@lobechat/types';++/**+ * Output lines that say a command CREATED the branch it moved to:+ *+ * - `git switch -c x` / `git checkout -b x` → `Switched to a new branch 'x'`+ * - `git worktree add -b x …` → `Preparing worktree (new branch 'x')`+ * - Claude Code `EnterWorktree` → `Created worktree at … on branch x.`+ *+ * Only these make the branch the conversation's own; switching to an+ * existing branch never does — someone else's PR may already sit on it.+ */+const CREATED_BRANCH_PATTERNS = [+ /Switched to a new branch ['"]([^'"\n]+)['"]/i,+ /\(new branch ['"]([^'"\n]+)['"]\)/i,+ /^Created worktree at .+? on branch (\S+?)\.? /m,+] as const;++export const parseCreatedBranch = (content?: string): string | undefined => {+ if (!content) return undefined;+ for (const pattern of CREATED_BRANCH_PATTERNS) {+ const branch = pattern.exec(content)?.[1];+ if (branch) return branch;+ }+ return undefined;+};++/**+ * Record `branch` as the conversation's own when the command created it and+ * the topic is now on it (`git.ownBranch`, Better Coding Experience). The run+ * end only asks GitHub for the PR of that branch.+ */+export const applyOwnBranchToConfig = (+ config: WorkingDirConfig | undefined,+ createdBranch: string | undefined,+): WorkingDirConfig | undefined => {+ if (!config?.git || !createdBranch || config.git.branch !== createdBranch) return config;+ if (config.git.ownBranch === createdBranch) return config;+ return { ...config, git: { ...config.git, ownBranch: createdBranch } };+};diff --git a/src/store/tool/slices/builtin/executors/pushedPullRequests.ts b/src/store/tool/slices/builtin/executors/pushedPullRequests.tsindex 0e59b704043..4d83a0975ef 100644--- a/src/store/tool/slices/builtin/executors/pushedPullRequests.ts+++ b/src/store/tool/slices/builtin/executors/pushedPullRequests.ts@@ -40,6 +40,7 @@ export const linkPushedPullRequests = async (params: {? [{headRefName,+ ...(pr.headRepoFullName ? { headRepoFullName: pr.headRepoFullName } : {}),isDraft: pr.isDraft,number: pr.number,state: pr.state,diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex 9e9af6772c7..e790ed6a5b5 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -11,6 +11,7 @@ import { getElectronStoreState } from '@/store/electron';import { getUserStoreState } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';+import { applyOwnBranchToConfig, parseCreatedBranch } from './ownBranch';import { linkPushedPullRequests } from './pushedPullRequests';import {applyBranchToConfig,@@ -42,6 +43,11 @@ import {/** Flags on `git worktree add` that consume the following token as their value. */const VALUE_FLAGS = new Set(['-b', '-B', '--reason']);const BRANCH_VALUE_FLAGS = new Set(['-b', '-B']);+/**+ * Branch flags that can only CREATE: `-C` / `-B` / `--force-create` also reset an+ * existing branch, so a successful run with them proves nothing about who made it.+ */+const CREATE_ONLY_BRANCH_FLAGS = new Set(['-b', '-c', '--create', '--orphan']);const BRANCH_SWITCH_VALUE_FLAGS = new Set(['-b','-B',@@ -105,13 +111,16 @@ const CC_SESSION_ENTER_MARKER = 'The session is now working in the worktree';interface WorktreeAddParseResult {branch?: string;+ /** `-b` named {@link branch}: git refuses it when the branch exists, so it is new. */+ createdBranch?: boolean;/** Resolved absolute path, present only when the command yielded a trustworthy literal. */path?: string;/** Positional commit-ish (often the checked-out branch) — hint for the device lookup. */ref?: string;}-type BranchSwitchInfo = { branch: string } | { detached: true };+/** `created`: a creation flag named the branch (`-c` / `-b` / `--orphan` …). */+type BranchSwitchInfo = { branch: string; created?: true } | { detached: true };const stripQuotes = (token: string): string => {if (token.length >= 2) {@@ -298,6 +307,7 @@ const parseGitBranchSwitchTokens = (if (!git || !GIT_BRANCH_SWITCH_SUBCOMMANDS.has(git.subcommand)) return undefined;let branch: string | undefined;+ let created = false;for (let i = 0; i < git.args.length; i += 1) {const token = git.args[i];if (DETACH_FLAGS.has(stripQuotes(token))) return { detached: true };@@ -305,6 +315,7 @@ const parseGitBranchSwitchTokens = (const branchFlag = getOptionValue(git.args, i, [...BRANCH_SWITCH_VALUE_FLAGS], env);if (branchFlag.value) {branch = normalizeBranch(branchFlag.value);+ created = CREATE_ONLY_BRANCH_FLAGS.has(stripQuotes(token).split('=')[0]);break;}if (branchFlag.skipNext) {@@ -326,7 +337,7 @@ const parseGitBranchSwitchTokens = (break;}- return branch ? { branch } : undefined;+ return branch ? { branch, ...(created ? { created: true as const } : {}) } : undefined;};const isGitBranchSwitchCommand = (tokens: string[]): boolean | undefined => {@@ -540,6 +551,10 @@ const parseGitPush = (return { branch: remoteBranch, remote: push.remote ?? 'origin' };};+/** The command runs a fallback when an earlier step fails (`a || b`). */+const hasFailureRecovery = (command: string | string[]): boolean =>+ (Array.isArray(command) ? command.join(' ') : command).includes('||');+/** Collapse `.`/`..` segments in a POSIX path without touching the filesystem. */const normalizePosix = (p: string): string => {const isAbs = p.startsWith('/');@@ -678,12 +693,14 @@ const parseGitWorktreeAddTokens = (// Positionals after `add`: first is the worktree path, second the commit-ish.let branch: string | undefined;+ let createdBranch = false;let path: string | undefined;let ref: string | undefined;for (; i < tokens.length; i += 1) {const token = tokens[i];if (BRANCH_VALUE_FLAGS.has(token)) {branch = resolveToken(tokens[i + 1] ?? '', env) || branch;+ createdBranch = CREATE_ONLY_BRANCH_FLAGS.has(token);i += 1; // skip this flag's valuecontinue;}@@ -706,6 +723,7 @@ const parseGitWorktreeAddTokens = (return {...(branch ? { branch } : {}),+ ...(branch && createdBranch ? { createdBranch: true } : {}),...(ref ? { ref } : {}),...(isLiteralPath(path) ? { path: resolveWorktreePath(path, baseCwd) } : {}),};@@ -977,6 +995,26 @@ export const recordGitCommandEffects = async (params: {nextConfig = applyPushToConfig(nextConfig, source, pushUpstream);}+ // A branch the agent created is the conversation's own: its PR may be looked up.+ // The creation shows in git's output, or — with `-q`, which prints nothing —+ // in the creation flag that named it. A chain that recovers from a failure+ // (`git switch -c x || git switch x`) succeeds whether or not the creation+ // did, so only git's own output can say so there.+ if (betterCoding) {+ const commandSaysCreated = !hasFailureRecovery(command);+ const created =+ parseCreatedBranch(resultContent) ??+ (commandSaysCreated && branchSwitch && 'created' in branchSwitch+ ? branchSwitch.branch+ : undefined) ??+ (() => {+ if (!commandSaysCreated) return undefined;+ const worktreeAdd = parseWorktreeAddInfo(command, source);+ return worktreeAdd?.createdBranch ? worktreeAdd.branch : undefined;+ })();+ nextConfig = applyOwnBranchToConfig(nextConfig, created);+ }+const prCreate = betterCoding ? undefined : parseGhPrCreate(command, resultContent);if (prCreate) {nextConfig = applyPullRequestToConfig(nextConfig, source, prCreate);@@ -1061,7 +1099,9 @@ export const recordWorktreeEnter = async (params: {const worktreeInfo = parseWorktreeEnterInfo(content);if (!worktreeInfo || !source || worktreeInfo.path === source) return;- const nextConfig = applyWorktreeAddToConfig(currentConfig, source, worktreeInfo);+ let nextConfig = applyWorktreeAddToConfig(currentConfig, source, worktreeInfo);+ if (labPreferSelectors.enableBetterCodingExperience(getUserStoreState()))+ nextConfig = applyOwnBranchToConfig(nextConfig, parseCreatedBranch(content))!;if (isEqual(currentConfig, nextConfig)) return;await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });