🤯 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(desktop): native pull request tab in the Working Sidebar (#19506)
Inneif2dcabe6048d
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.tsindex f38969b7892..48f9b951e9d 100644--- a/apps/desktop/src/main/controllers/GitCtr.ts+++ b/apps/desktop/src/main/controllers/GitCtr.ts@@ -9,6 +9,11 @@ import type {GitDeleteBranchResult,GitFileRevertResult,GitLinkedPullRequestResult,+ GitPullRequestAction,+ GitPullRequestActionResult,+ GitPullRequestActivity,+ GitPullRequestDetailResult,+ GitPullRequestMergeContext,GitPullResult,GitPushResult,GitRemoteBranchListItem,@@ -63,6 +68,47 @@ export default class GitController extends ControllerModule {return computeLinkedPullRequest(payload);}+ @IpcMethod()+ async getPullRequestDetail(payload: {+ coreOnly?: boolean;+ number: number;+ path: string;+ }): Promise<GitPullRequestDetailResult> {+ const { getPullRequestDetail: computePullRequestDetail } = await loadGit();+ return computePullRequestDetail(payload);+ }++ @IpcMethod()+ async getPullRequestActivity(payload: {+ number: number;+ path: string;+ }): Promise<GitPullRequestActivity> {+ const { getPullRequestActivity: computePullRequestActivity } = await loadGit();+ return computePullRequestActivity(payload);+ }++ @IpcMethod()+ async getPullRequestMergeContext(payload: {+ baseRefName: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ }): Promise<GitPullRequestMergeContext> {+ const { getPullRequestMergeContext: computeMergeContext } = await loadGit();+ return computeMergeContext(payload);+ }++ @IpcMethod()+ async runPullRequestAction(payload: {+ action: GitPullRequestAction;+ number: number;+ path: string;+ }): Promise<GitPullRequestActionResult> {+ const { runPullRequestAction: runPullRequestActionRpc } = await loadGit();+ return runPullRequestActionRpc(payload);+ }+@IpcMethod()async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {const { listGitBranches: computeListGitBranches } = await loadGit();diff --git a/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.tsnew file mode 100644index 00000000000..331784994ac--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts@@ -0,0 +1,66 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ findByDeviceId: vi.fn(),+ runGitPullRequestAction: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findByDeviceId = mocks.findByDeviceId;+ findWorkspaceDeviceById = async () => ({ deviceId: 'device' });+ },+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: { runGitPullRequestAction: mocks.runGitPullRequestAction },+}));++describe('PR mutation workspace boundary', () => {+ const caller = deviceRouter.createCaller({ userId: 'member', workspaceId: 'workspace' } as never);+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/approved' }] });+ mocks.runGitPullRequestAction.mockResolvedValue({ success: true });+ });++ it('rejects another repository before sending any command to the device', async () => {+ await expect(+ caller.runGitPullRequestAction({+ action: { type: 'close' },+ deviceId: 'device',+ number: 42,+ path: '/other',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ });++ it('allows a repository inside the approved root', async () => {+ await expect(+ caller.runGitPullRequestAction({+ action: { type: 'close' },+ deviceId: 'device',+ number: 42,+ path: '/approved/repo',+ }),+ ).resolves.toEqual({ success: true });+ });++ it('rejects a merge without the displayed head commit', async () => {+ await expect(+ caller.runGitPullRequestAction({+ // @ts-expect-error Old clients must fail closed instead of merging an unseen head.+ action: { method: 'squash', type: 'merge' },+ deviceId: 'device',+ number: 42,+ path: '/approved',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 2c4c89c4bd4..0334ccc0e47 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -255,6 +255,62 @@ export const deviceRouter = router({return result ?? null;}),+ gitPullRequestDetail: deviceProcedure+ .input(+ z.object({+ coreOnly: z.boolean().optional(),+ deviceId: z.string(),+ number: z.number().int().positive(),+ path: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestDetail({+ coreOnly: input.coreOnly,+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),++ gitPullRequestActivity: deviceProcedure+ .input(+ z.object({ deviceId: z.string(), number: z.number().int().positive(), path: z.string() }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestActivity({+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),++ gitPullRequestMergeContext: deviceProcedure+ .input(+ z.object({+ baseRefName: z.string(),+ deviceId: z.string(),+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ number: z.number().int().positive(),+ path: z.string(),+ repo: z.object({ name: z.string(), owner: z.string() }),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestMergeContext({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+gitWorkingTreeStatus: deviceProcedure.input(z.object({ deviceId: z.string(), path: z.string() })).query(async ({ ctx, input }) => {@@ -527,6 +583,52 @@ export const deviceRouter = router({}),),+ /**+ * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a+ * directory on a remote device, via the device's `runPullRequestAction` RPC.+ */+ runGitPullRequestAction: deviceProcedure+ .input(+ z.object({+ action: z.discriminatedUnion('type', [+ z.object({+ admin: z.boolean().optional(),+ deleteBranch: z.boolean().optional(),+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ method: z.enum(['squash', 'merge', 'rebase']),+ type: z.literal('merge'),+ }),+ z.object({+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ method: z.enum(['squash', 'merge', 'rebase']),+ type: z.literal('autoMerge'),+ }),+ z.object({ type: z.literal('disableAutoMerge') }),+ z.object({ method: z.enum(['merge', 'rebase']), type: z.literal('updateBranch') }),+ z.object({ type: z.literal('ready') }),+ z.object({ body: z.string(), type: z.literal('comment') }),+ z.object({ type: z.literal('close') }),+ z.object({ type: z.literal('reopen') }),+ z.object({ head: z.string(), type: z.literal('deleteBranch') }),+ z.object({ base: z.string(), type: z.literal('changeBase') }),+ ]),+ deviceId: z.string(),+ number: z.number().int().positive(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertWorkspaceRootApproved(ctx.deviceModel, input.deviceId, input.path);+ return deviceGateway.runGitPullRequestAction({+ action: input.action,+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+/*** Working-tree (unstaged) per-file patches for a directory on a remote device,* via the device's `getGitWorkingTreePatches` RPC. Powers the web/remote Reviewdiff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 5404d145846..6b760d61026 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -23,6 +23,11 @@ import type {DeviceGitDeleteBranchResult,DeviceGitFileRevertResult,DeviceGitLinkedPullRequestResult,+ DeviceGitPullRequestAction,+ DeviceGitPullRequestActionResult,+ DeviceGitPullRequestActivity,+ DeviceGitPullRequestDetailResult,+ DeviceGitPullRequestMergeContext,DeviceGitRemoteBranchListItem,DeviceGitRemoveWorktreeResult,DeviceGitRenameBranchResult,@@ -457,6 +462,67 @@ export class DeviceGateway {});}+ /** Full detail of a pull request in a directory on a remote device. */+ gitPullRequestDetail(params: {+ coreOnly?: boolean;+ deviceId: string;+ number: number;+ path: string;+ userId: string;+ workspaceId?: string;+ }) {+ return this.invokeDeviceRead<DeviceGitPullRequestDetailResult>(+ 'getPullRequestDetail',+ { ...params, timeout: 20_000 },+ {+ coreOnly: params.coreOnly,+ number: params.number,+ path: params.path,+ },+ );+ }++ gitPullRequestActivity(params: {+ deviceId: string;+ number: number;+ path: string;+ userId: string;+ workspaceId?: string;+ }) {+ return this.invokeDeviceRead<DeviceGitPullRequestActivity>(+ 'getPullRequestActivity',+ { ...params, timeout: 20_000 },+ {+ number: params.number,+ path: params.path,+ },+ );+ }++ /** Branch-protection / permission context for a pull request on a remote device. */+ gitPullRequestMergeContext(params: {+ baseRefName: string;+ deviceId: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ userId: string;+ workspaceId?: string;+ }) {+ return this.invokeDeviceRead<DeviceGitPullRequestMergeContext>(+ 'getPullRequestMergeContext',+ { ...params, timeout: 20_000 },+ {+ baseRefName: params.baseRefName,+ headRefOid: params.headRefOid,+ number: params.number,+ path: params.path,+ repo: params.repo,+ },+ );+ }+/** Working-tree dirty-file counts for a directory on a remote device. */gitWorkingTreeStatus(params: {deviceId: string;@@ -849,6 +915,42 @@ export class DeviceGateway {}}+ /**+ * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a+ * directory on a remote device via the `runPullRequestAction` device RPC.+ * Merge can take a while, so it gets the same 65s budget as push/pull.+ */+ async runGitPullRequestAction(params: {+ action: DeviceGitPullRequestAction;+ deviceId: string;+ number: number;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ }): Promise<DeviceGitPullRequestActionResult> {+ const { userId, deviceId, path, number, action, timeout = 65_000, workspaceId } = params;+ const client = this.getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitPullRequestActionResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'runPullRequestAction', params: { action, number, path } },+ );++ if (!result.success || !result.data) {+ log('runGitPullRequestAction: failed for deviceId=%s — %s', deviceId, result.error);+ return { error: result.error || 'Pull request action failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('runGitPullRequestAction: error for deviceId=%s — %O', deviceId, error);+ return { error: (error as Error)?.message || 'Pull request action failed', success: false };+ }+ }+/*** Working-tree (unstaged) per-file patches for a directory on a remote device* via the `getGitWorkingTreePatches` device RPC, so the web/remote Review paneldiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4981005e2ef..6ab337a47c1 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2537,6 +2537,103 @@"workingPanel.overview.workspace.empty": "No workspace selected","workingPanel.overview.workspace.emptyDesc": "Choose a working directory from the runtime bar","workingPanel.overview.worktree.of": "Worktree of {{name}}",+ "workingPanel.pr.action.arming": "Arming auto-merge…",+ "workingPanel.pr.action.autoMerge": "Auto-merge when ready",+ "workingPanel.pr.action.bypassSuffix": "bypass rules",+ "workingPanel.pr.action.calculating": "Calculating…",+ "workingPanel.pr.action.conflicting": "Resolve conflicts to merge",+ "workingPanel.pr.action.deleteBranch": "Delete branch",+ "workingPanel.pr.action.disableAutoMerge": "Disable",+ "workingPanel.pr.action.merging": "Merging…",+ "workingPanel.pr.action.push_one": "Push {{count}} commit",+ "workingPanel.pr.action.push_other": "Push {{count}} commits",+ "workingPanel.pr.action.pushing": "Pushing…",+ "workingPanel.pr.action.ready": "Mark ready for review",+ "workingPanel.pr.action.readying": "Marking ready…",+ "workingPanel.pr.action.reopen": "Reopen pull request",+ "workingPanel.pr.action.updateBranch": "Update branch",+ "workingPanel.pr.action.updateBranch.merge": "Update with merge commit",+ "workingPanel.pr.action.updateBranch.rebase": "Update with rebase",+ "workingPanel.pr.action.updating": "Updating branch…",+ "workingPanel.pr.action.waiting": "Waiting for checks…",+ "workingPanel.pr.activity.approved": "approved",+ "workingPanel.pr.activity.changesRequested": "requested changes",+ "workingPanel.pr.activity.commented": "reviewed",+ "workingPanel.pr.activity.committed": "committed",+ "workingPanel.pr.activity.dismissed": "review dismissed",+ "workingPanel.pr.bypass": "Merge without waiting for requirements",+ "workingPanel.pr.check.optional": "optional",+ "workingPanel.pr.check.queued": "queued",+ "workingPanel.pr.checks.failing_one": "{{count}} failing",+ "workingPanel.pr.checks.failing_other": "{{count}} failing",+ "workingPanel.pr.checks.running_one": "{{count}} running",+ "workingPanel.pr.checks.running_other": "{{count}} running",+ "workingPanel.pr.composer.placeholder": "Write a comment…",+ "workingPanel.pr.composer.submit": "Comment",+ "workingPanel.pr.dismiss": "Dismiss",+ "workingPanel.pr.error.load": "Could not load this pull request",+ "workingPanel.pr.files.openReview": "Open diff in Review",+ "workingPanel.pr.ghMissing.desc": "Install gh and run gh auth login to load pull requests here.",+ "workingPanel.pr.ghMissing.open": "Open in Browser",+ "workingPanel.pr.ghMissing.retry": "Check again",+ "workingPanel.pr.ghMissing.title": "GitHub CLI isn't set up on this device",+ "workingPanel.pr.header.changeBase": "Change base branch",+ "workingPanel.pr.header.commits_one": "{{count}} commit",+ "workingPanel.pr.header.commits_other": "{{count}} commits",+ "workingPanel.pr.hint.autoMerge": "Will {{method}} once checks pass. Cancels on new commits or a changes-requested review.",+ "workingPanel.pr.hint.blocked": "Push a fix or wait for requirements; this refreshes automatically.",+ "workingPanel.pr.hint.bypass": "Bypass is recorded on GitHub and visible in the audit log.",+ "workingPanel.pr.hint.calculating": "GitHub is recomputing after the last push; usually a few seconds.",+ "workingPanel.pr.hint.merge_one": "Merges {{count}} commit into {{base}}.",+ "workingPanel.pr.hint.merge_other": "Merges {{count}} commits into {{base}}.",+ "workingPanel.pr.hint.merged": "{{head}} is safe to delete.",+ "workingPanel.pr.hint.readOnly": "Only maintainers of {{repo}} can merge this pull request.",+ "workingPanel.pr.menu.close": "Close pull request",+ "workingPanel.pr.menu.copied": "Link copied",+ "workingPanel.pr.menu.copyLink": "Copy link",+ "workingPanel.pr.menu.openOnGithub": "Open on GitHub",+ "workingPanel.pr.menu.reopen": "Reopen pull request",+ "workingPanel.pr.method.merge": "Create a merge commit",+ "workingPanel.pr.method.merge.desc": "Keep all commits and add a merge commit on {{base}}.",+ "workingPanel.pr.method.rebase": "Rebase and merge",+ "workingPanel.pr.method.rebase.desc": "Replay the commits onto {{base}}.",+ "workingPanel.pr.method.squash": "Squash and merge",+ "workingPanel.pr.method.squash.desc": "Combine the commits into one on {{base}}.",+ "workingPanel.pr.reason.behind": "Branch is behind {{base}}",+ "workingPanel.pr.reason.changesRequested": "Changes requested by {{authors}}",+ "workingPanel.pr.reason.checksFailing_one": "{{count}} required check failing",+ "workingPanel.pr.reason.checksFailing_other": "{{count}} required checks failing",+ "workingPanel.pr.reason.checksPending": "Checks running",+ "workingPanel.pr.reason.conflicts": "Conflicts with {{base}}",+ "workingPanel.pr.reason.localAhead_one": "{{count}} local commit not pushed",+ "workingPanel.pr.reason.localAhead_other": "{{count}} local commits not pushed",+ "workingPanel.pr.reason.localDirty_one": "{{count}} uncommitted file",+ "workingPanel.pr.reason.localDirty_other": "{{count}} uncommitted files",+ "workingPanel.pr.reason.optionalFailing_one": "{{count}} optional check failing",+ "workingPanel.pr.reason.optionalFailing_other": "{{count}} optional checks failing",+ "workingPanel.pr.reason.reviewRequired": "Review required",+ "workingPanel.pr.reason.rules": "Blocked by branch rules",+ "workingPanel.pr.section.activity": "Activity",+ "workingPanel.pr.section.checks": "Checks",+ "workingPanel.pr.section.commits": "Commits",+ "workingPanel.pr.section.description": "Description",+ "workingPanel.pr.section.files": "Files changed",+ "workingPanel.pr.state.closed": "Closed",+ "workingPanel.pr.state.draft": "Draft",+ "workingPanel.pr.state.merged": "Merged",+ "workingPanel.pr.state.open": "Open",+ "workingPanel.pr.status.autoMerge": "Auto-merge enabled ({{method}})",+ "workingPanel.pr.status.blocked": "Merging is blocked",+ "workingPanel.pr.status.bypass": "Bypassing branch protection",+ "workingPanel.pr.status.calculating": "Checking mergeability…",+ "workingPanel.pr.status.closed": "Closed without merging",+ "workingPanel.pr.status.conflicts": "This branch has conflicts with {{base}}",+ "workingPanel.pr.status.draft": "Still a draft",+ "workingPanel.pr.status.error": "Merge failed: {{message}}",+ "workingPanel.pr.status.merged": "Merged",+ "workingPanel.pr.status.ready": "Ready to merge",+ "workingPanel.pr.status.unstable": "Some checks were not successful",+ "workingPanel.pr.status.waiting": "Waiting for checks","workingPanel.progress": "Progress","workingPanel.progress.allCompleted": "All tasks completed","workingPanel.resources": "Resources",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 07ee2ae0e49..b6c1a02ed33 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2537,6 +2537,103 @@"workingPanel.overview.workspace.empty": "尚未选择工作区","workingPanel.overview.workspace.emptyDesc": "请从运行时栏中选择工作目录","workingPanel.overview.worktree.of": "{{name}} 的工作树",+ "workingPanel.pr.action.arming": "正在开启自动合并…",+ "workingPanel.pr.action.autoMerge": "就绪后自动合并",+ "workingPanel.pr.action.bypassSuffix": "绕过规则",+ "workingPanel.pr.action.calculating": "计算中…",+ "workingPanel.pr.action.conflicting": "解决冲突后才能合并",+ "workingPanel.pr.action.deleteBranch": "删除分支",+ "workingPanel.pr.action.disableAutoMerge": "关闭",+ "workingPanel.pr.action.merging": "正在合并…",+ "workingPanel.pr.action.push_one": "推送 {{count}} 个提交",+ "workingPanel.pr.action.push_other": "推送 {{count}} 个提交",+ "workingPanel.pr.action.pushing": "正在推送…",+ "workingPanel.pr.action.ready": "标记为可评审",+ "workingPanel.pr.action.readying": "正在标记…",+ "workingPanel.pr.action.reopen": "重新打开 Pull Request",+ "workingPanel.pr.action.updateBranch": "更新分支",+ "workingPanel.pr.action.updateBranch.merge": "以合并提交更新",+ "workingPanel.pr.action.updateBranch.rebase": "以变基更新",+ "workingPanel.pr.action.updating": "正在更新分支…",+ "workingPanel.pr.action.waiting": "等待检查完成…",+ "workingPanel.pr.activity.approved": "批准了",+ "workingPanel.pr.activity.changesRequested": "请求修改",+ "workingPanel.pr.activity.commented": "评审了",+ "workingPanel.pr.activity.committed": "提交了",+ "workingPanel.pr.activity.dismissed": "评审已撤销",+ "workingPanel.pr.bypass": "不等待要求满足直接合并",+ "workingPanel.pr.check.optional": "可选",+ "workingPanel.pr.check.queued": "排队中",+ "workingPanel.pr.checks.failing_one": "{{count}} 项失败",+ "workingPanel.pr.checks.failing_other": "{{count}} 项失败",+ "workingPanel.pr.checks.running_one": "{{count}} 项运行中",+ "workingPanel.pr.checks.running_other": "{{count}} 项运行中",+ "workingPanel.pr.composer.placeholder": "写下评论…",+ "workingPanel.pr.composer.submit": "评论",+ "workingPanel.pr.dismiss": "忽略",+ "workingPanel.pr.error.load": "无法加载此 Pull Request",+ "workingPanel.pr.files.openReview": "在 Review 中查看差异",+ "workingPanel.pr.ghMissing.desc": "安装 gh 并运行 gh auth login 后即可在此加载 Pull Request。",+ "workingPanel.pr.ghMissing.open": "在浏览器中打开",+ "workingPanel.pr.ghMissing.retry": "重新检查",+ "workingPanel.pr.ghMissing.title": "此设备尚未配置 GitHub CLI",+ "workingPanel.pr.header.changeBase": "修改目标分支",+ "workingPanel.pr.header.commits_one": "{{count}} 个提交",+ "workingPanel.pr.header.commits_other": "{{count}} 个提交",+ "workingPanel.pr.hint.autoMerge": "检查通过后将执行{{method}}合并。有新提交或收到「请求修改」评审时自动取消。",+ "workingPanel.pr.hint.blocked": "推送修复或等待要求满足;此处会自动刷新。",+ "workingPanel.pr.hint.bypass": "绕过操作会记录在 GitHub 上,并在审计日志中可见。",+ "workingPanel.pr.hint.calculating": "GitHub 正在根据最近一次推送重新计算,通常只需几秒。",+ "workingPanel.pr.hint.merge_one": "将 {{count}} 个提交合并到 {{base}}。",+ "workingPanel.pr.hint.merge_other": "将 {{count}} 个提交合并到 {{base}}。",+ "workingPanel.pr.hint.merged": "{{head}} 可以安全删除。",+ "workingPanel.pr.hint.readOnly": "只有 {{repo}} 的维护者才能合并此 Pull Request。",+ "workingPanel.pr.menu.close": "关闭 Pull Request",+ "workingPanel.pr.menu.copied": "链接已复制",+ "workingPanel.pr.menu.copyLink": "复制链接",+ "workingPanel.pr.menu.openOnGithub": "在 GitHub 上打开",+ "workingPanel.pr.menu.reopen": "重新打开 Pull Request",+ "workingPanel.pr.method.merge": "创建合并提交",+ "workingPanel.pr.method.merge.desc": "保留全部提交,并在 {{base}} 上添加一个合并提交。",+ "workingPanel.pr.method.rebase": "变基并合并",+ "workingPanel.pr.method.rebase.desc": "将提交重放到 {{base}} 上。",+ "workingPanel.pr.method.squash": "压缩并合并",+ "workingPanel.pr.method.squash.desc": "将所有提交压缩为 {{base}} 上的一个提交。",+ "workingPanel.pr.reason.behind": "分支落后于 {{base}}",+ "workingPanel.pr.reason.changesRequested": "{{authors}} 请求修改",+ "workingPanel.pr.reason.checksFailing_one": "{{count}} 个必需检查失败",+ "workingPanel.pr.reason.checksFailing_other": "{{count}} 个必需检查失败",+ "workingPanel.pr.reason.checksPending": "检查运行中",+ "workingPanel.pr.reason.conflicts": "与 {{base}} 存在冲突",+ "workingPanel.pr.reason.localAhead_one": "{{count}} 个本地提交未推送",+ "workingPanel.pr.reason.localAhead_other": "{{count}} 个本地提交未推送",+ "workingPanel.pr.reason.localDirty_one": "{{count}} 个文件未提交",+ "workingPanel.pr.reason.localDirty_other": "{{count}} 个文件未提交",+ "workingPanel.pr.reason.optionalFailing_one": "{{count}} 个可选检查失败",+ "workingPanel.pr.reason.optionalFailing_other": "{{count}} 个可选检查失败",+ "workingPanel.pr.reason.reviewRequired": "需要评审",+ "workingPanel.pr.reason.rules": "被分支规则阻止",+ "workingPanel.pr.section.activity": "动态",+ "workingPanel.pr.section.checks": "检查",+ "workingPanel.pr.section.commits": "提交",+ "workingPanel.pr.section.description": "描述",+ "workingPanel.pr.section.files": "变更文件",+ "workingPanel.pr.state.closed": "已关闭",+ "workingPanel.pr.state.draft": "草稿",+ "workingPanel.pr.state.merged": "已合并",+ "workingPanel.pr.state.open": "开放",+ "workingPanel.pr.status.autoMerge": "已开启自动合并({{method}})",+ "workingPanel.pr.status.blocked": "合并被阻止",+ "workingPanel.pr.status.bypass": "正在绕过分支保护",+ "workingPanel.pr.status.calculating": "正在检查可合并性…",+ "workingPanel.pr.status.closed": "已关闭,未合并",+ "workingPanel.pr.status.conflicts": "此分支与 {{base}} 存在冲突",+ "workingPanel.pr.status.draft": "仍是草稿",+ "workingPanel.pr.status.error": "合并失败:{{message}}",+ "workingPanel.pr.status.merged": "已合并",+ "workingPanel.pr.status.ready": "可以合并",+ "workingPanel.pr.status.unstable": "部分检查未通过",+ "workingPanel.pr.status.waiting": "等待检查完成","workingPanel.progress": "进度","workingPanel.progress.allCompleted": "所有任务已完成","workingPanel.resources": "资源",diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 0cb44cb5622..a6b14893743 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -10,6 +10,10 @@ import {getGitWorkingTreePatches,getGitWorkingTreeStatus,getLinkedPullRequest,+ getPullRequestActivity,+ getPullRequestDetail,+ getPullRequestMergeContext,+ type GitPullRequestAction,listGitBranches,listGitRemoteBranches,listGitWorktrees,@@ -18,6 +22,7 @@ import {removeGitWorktree,renameGitBranch,revertGitFile,+ runPullRequestAction,} from '@lobechat/local-file-shell/git';import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';@@ -69,6 +74,10 @@ export const DEVICE_RPC_METHODS = ['writeLocalFile','getGitBranch','getLinkedPullRequest',+ 'getPullRequestDetail',+ 'getPullRequestActivity',+ 'getPullRequestMergeContext',+ 'runPullRequestAction','getGitWorkingTreeStatus','getGitWorkingTreeFiles','getGitWorkingTreePatches',@@ -202,6 +211,31 @@ export const executeDeviceRpc = async ();}+ case 'getPullRequestDetail': {+ return getPullRequestDetail(params as { coreOnly?: boolean; number: number; path: string });+ }+ case 'getPullRequestActivity': {+ return getPullRequestActivity(params as { number: number; path: string });+ }++ case 'getPullRequestMergeContext': {+ return getPullRequestMergeContext(+ params as {+ baseRefName: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ },+ );+ }++ case 'runPullRequestAction': {+ return runPullRequestAction(+ params as { action: GitPullRequestAction; number: number; path: string },+ );+ }+case 'getGitWorkingTreeStatus': {return getGitWorkingTreeStatus((params as { path: string }).path);}diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.tsindex 0a080d11ddf..bed692bf7c7 100644--- a/packages/electron-client-ipc/src/types/git.ts+++ b/packages/electron-client-ipc/src/types/git.ts@@ -47,6 +47,111 @@ export interface GitLinkedPullRequestResult {upstream?: GitUpstreamRef;}+export interface GitPullRequestCheck {+ completedAt?: string;+ detailsUrl?: string;+ name: string;+ required: boolean;+ startedAt?: string;+ status: 'cancelled' | 'failure' | 'neutral' | 'pending' | 'skipped' | 'success';+}++export interface GitPullRequestComment {+ author: string;+ body: string;+ createdAt: string;+ id: string;+}++export interface GitPullRequestReview {+ author: string;+ state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'DISMISSED' | 'PENDING';+ submittedAt: string;+}++export interface GitPullRequestCommit {+ author: string;+ committedAt: string;+ message: string;+ sha: string;+}++export interface GitPullRequestDetail {+ additions: number;+ author: string;+ autoMerge?: { method: 'merge' | 'rebase' | 'squash' } | null;+ baseBehindBy: number;+ baseRefName: string;+ body: string;+ changedFiles: number;+ checks: GitPullRequestCheck[];+ comments: GitPullRequestComment[];+ commits: GitPullRequestCommit[];+ deletions: number;+ headRefName: string;+ headRefOid: string;+ isCrossRepository: boolean;+ isDraft: boolean;+ mergeable: 'CONFLICTING' | 'MERGEABLE' | 'UNKNOWN';+ mergedAt?: string;+ mergeStateStatus:+ 'BEHIND' | 'BLOCKED' | 'CLEAN' | 'DIRTY' | 'DRAFT' | 'HAS_HOOKS' | 'UNKNOWN' | 'UNSTABLE';+ number: number;+ repo: { name: string; owner: string };+ reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null;+ reviews: GitPullRequestReview[];+ state: 'closed' | 'merged' | 'open';+ title: string;+ url: string;+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++export type GitPullRequestActivity = Pick<GitPullRequestDetail, 'comments' | 'commits' | 'reviews'>;++export interface GitPullRequestDetailResult {+ detail: GitPullRequestDetail | null;+ status: GitLinkedPullRequestLookupStatus;+}++export type GitPullRequestMergeMethod = 'merge' | 'rebase' | 'squash';++/**+ * Slow, permission-dependent merge context resolved separately from the PR+ * detail so the pane can paint before branch protection / compare calls land.+ */+export interface GitPullRequestMergeContext {+ /** Commits the base branch has that the PR head does not. */+ baseBehindBy: number;+ /** Status-check contexts required by branch protection on the base branch. */+ requiredChecks: string[];+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++export type GitPullRequestAction =+ | {+ admin?: boolean;+ deleteBranch?: boolean;+ headRefOid: string;+ method: GitPullRequestMergeMethod;+ type: 'merge';+ }+ | { headRefOid: string; method: GitPullRequestMergeMethod; type: 'autoMerge' }+ | { type: 'disableAutoMerge' }+ | { method: 'merge' | 'rebase'; type: 'updateBranch' }+ | { type: 'ready' }+ | { body: string; type: 'comment' }+ | { type: 'close' }+ | { type: 'reopen' }+ | { head: string; type: 'deleteBranch' }+ | { base: string; type: 'changeBase' };++export interface GitPullRequestActionResult {+ error?: string;+ success: boolean;+}+export interface GitBranchListItem {current: boolean;name: string;diff --git a/packages/local-file-shell/src/git/__tests__/pullRequest.test.ts b/packages/local-file-shell/src/git/__tests__/pullRequest.test.tsnew file mode 100644index 00000000000..7d4b44f0be4--- /dev/null+++ b/packages/local-file-shell/src/git/__tests__/pullRequest.test.ts@@ -0,0 +1,360 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getPullRequestActivity,+ getPullRequestDetail,+ normalizeMergeContext,+ normalizePullRequestDetail,+ pullRequestActionArgs,+ repoFromPullRequestUrl,+ runPullRequestAction,+} from '../pullRequest';+import type { GitPullRequestAction } from '../types';++const childProcessMocks = vi.hoisted(() => ({+ execFileAsync: vi.fn(),+}));++vi.mock('node:child_process', () => {+ const execFile = Object.assign(vi.fn(), {+ [Symbol.for('nodejs.util.promisify.custom')]: childProcessMocks.execFileAsync,+ });++ return { execFile };+});++describe('normalizePullRequestDetail', () => {+ const repo = { name: 'lobe-chat', owner: 'lobehub' };++ const basePayload = {+ additions: 12,+ author: { login: 'innei' },+ autoMergeRequest: null as { mergeMethod?: string | null } | null,+ baseRefName: 'main',+ body: 'body text',+ changedFiles: 3,+ comments: [+ { author: { login: 'bot' }, body: 'lgtm', createdAt: '2026-09-01T00:00:00Z', id: 'c1' },+ ],+ commits: [+ {+ authors: [{ login: 'innei' }],+ committedDate: '2026-09-01T00:00:00Z',+ messageHeadline: 'fix bug',+ oid: 'abc123',+ },+ ],+ deletions: 4,+ headRefName: 'fix/bug',+ headRefOid: 'a'.repeat(40),+ isCrossRepository: true,+ isDraft: false,+ mergeable: 'MERGEABLE',+ mergedAt: null as string | null,+ mergeStateStatus: 'CLEAN',+ number: 42,+ reviewDecision: 'APPROVED',+ reviews: [+ { author: { login: 'reviewer' }, state: 'APPROVED', submittedAt: '2026-09-01T00:00:00Z' },+ ],+ state: 'OPEN',+ statusCheckRollup: [+ {+ completedAt: '2026-09-01T00:01:00Z',+ conclusion: 'success',+ detailsUrl: 'https://ci/run/1',+ name: 'build',+ startedAt: '2026-09-01T00:00:00Z',+ status: 'completed',+ },+ { context: 'legacy-status', state: 'pending', targetUrl: 'https://ci/run/2' },+ ],+ title: 'Fix a bug',+ url: 'https://github.com/lobehub/lobe-chat/pull/42',+ };++ it('normalizes a mixed CheckRun/StatusContext payload; required is resolved by merge context', () => {+ const detail = normalizePullRequestDetail(basePayload, repo);++ expect(detail.isCrossRepository).toBe(true);+ expect(detail.headRefOid).toBe(basePayload.headRefOid);+ expect(detail.checks).toEqual([+ {+ completedAt: '2026-09-01T00:01:00Z',+ detailsUrl: 'https://ci/run/1',+ name: 'build',+ required: false,+ startedAt: '2026-09-01T00:00:00Z',+ status: 'success',+ },+ {+ detailsUrl: 'https://ci/run/2',+ name: 'legacy-status',+ required: false,+ status: 'pending',+ },+ ]);+ });++ it('reports merged state from mergedAt regardless of raw state casing', () => {+ const detail = normalizePullRequestDetail(+ { ...basePayload, mergedAt: '2026-09-02T00:00:00Z', state: 'OPEN' },+ repo,+ );++ expect(detail.state).toBe('merged');+ expect(detail.mergedAt).toBe('2026-09-02T00:00:00Z');+ });++ it('maps closed and open states', () => {+ expect(normalizePullRequestDetail({ ...basePayload, state: 'CLOSED' }, repo).state).toBe(+ 'closed',+ );+ expect(normalizePullRequestDetail(basePayload, repo).state).toBe('open');+ });++ it('maps autoMergeRequest to a lowercased method', () => {+ const detail = normalizePullRequestDetail(+ { ...basePayload, autoMergeRequest: { mergeMethod: 'SQUASH' } },+ repo,+ );++ expect(detail.autoMerge).toEqual({ method: 'squash' });+ });++ it('leaves permission and base drift unset until merge context resolves', () => {+ expect(normalizePullRequestDetail(basePayload, repo)).toMatchObject({+ baseBehindBy: 0,+ viewerCanBypass: false,+ viewerCanWrite: false,+ });+ });+});++describe('repoFromPullRequestUrl', () => {+ it('parses owner and repo from the PR url', () => {+ expect(repoFromPullRequestUrl('https://github.com/lobehub/lobe-chat/pull/42')).toEqual({+ name: 'lobe-chat',+ owner: 'lobehub',+ });+ expect(repoFromPullRequestUrl('')).toEqual({ name: '', owner: '' });+ });+});++describe('normalizeMergeContext', () => {+ const payload = (viewerPermission: string, contexts: string[] | null = ['ci']) => ({+ data: {+ repository: {+ pullRequest: {+ baseRef: {+ branchProtectionRule: { requiredStatusCheckContexts: contexts },+ name: 'main',+ },+ headRefOid: 'a'.repeat(40),+ },+ viewerPermission,+ },+ },+ });++ it.each([+ ['READ', false, false],+ ['WRITE', true, false],+ ['MAINTAIN', true, false],+ ['ADMIN', true, true],+ ])('maps %s permission', (permission, canWrite, canBypass) => {+ expect(normalizeMergeContext(payload(permission), 2)).toEqual({+ baseBehindBy: 2,+ requiredChecks: ['ci'],+ viewerCanBypass: canBypass,+ viewerCanWrite: canWrite,+ });+ });++ it('treats a missing protection rule as no required checks', () => {+ expect(normalizeMergeContext(payload('WRITE', null), 0).requiredChecks).toEqual([]);+ expect(normalizeMergeContext({}, 0)).toMatchObject({+ requiredChecks: [],+ viewerCanWrite: false,+ });+ });+});++describe('pullRequestActionArgs', () => {+ const cases: [GitPullRequestAction, string[][]][] = [+ [+ { headRefOid: 'a'.repeat(40), method: 'squash', type: 'merge' },+ [['pr', 'merge', '42', '--squash', '--match-head-commit', 'a'.repeat(40)]],+ ],+ [+ {+ admin: true,+ deleteBranch: true,+ headRefOid: 'a'.repeat(40),+ method: 'squash',+ type: 'merge',+ },+ [+ [+ 'pr',+ 'merge',+ '42',+ '--squash',+ '--match-head-commit',+ 'a'.repeat(40),+ '--admin',+ '--delete-branch',+ ],+ ],+ ],+ [+ { headRefOid: 'a'.repeat(40), method: 'rebase', type: 'autoMerge' },+ [['pr', 'merge', '42', '--auto', '--rebase', '--match-head-commit', 'a'.repeat(40)]],+ ],+ [{ type: 'disableAutoMerge' }, [['pr', 'merge', '42', '--disable-auto']]],+ [{ method: 'rebase', type: 'updateBranch' }, [['pr', 'update-branch', '42', '--rebase']]],+ [{ method: 'merge', type: 'updateBranch' }, [['pr', 'update-branch', '42']]],+ [{ type: 'ready' }, [['pr', 'ready', '42']]],+ [{ body: 'nice', type: 'comment' }, [['pr', 'comment', '42', '--body', 'nice']]],+ [{ type: 'close' }, [['pr', 'close', '42']]],+ [{ type: 'reopen' }, [['pr', 'reopen', '42']]],+ [+ { head: 'fix/bug', type: 'deleteBranch' },+ [['api', '-X', 'DELETE', 'repos/{owner}/{repo}/git/refs/heads/fix/bug']],+ ],+ [{ base: 'canary', type: 'changeBase' }, [['pr', 'edit', '42', '--base', 'canary']]],+ ];++ it.each(cases)('maps %o to argv', (action, expected) => {+ expect(pullRequestActionArgs(42, action)).toEqual(expected);+ });++ it.each([['../fix'], ['fix/../../etc'], ['fix bug'], ['fix;rm -rf']])(+ 'rejects an unsafe branch name %s for deleteBranch and changeBase',+ (name) => {+ expect(() => pullRequestActionArgs(42, { head: name, type: 'deleteBranch' })).toThrow(+ 'Invalid branch name',+ );+ expect(() => pullRequestActionArgs(42, { base: name, type: 'changeBase' })).toThrow(+ 'Invalid branch name',+ );+ },+ );+});++describe('runPullRequestAction head protection', () => {+ beforeEach(() => {+ childProcessMocks.execFileAsync.mockReset();+ });++ it.each(['merge', 'autoMerge'] as const)(+ 'rejects missing or invalid heads before executing %s',+ async (type) => {+ for (const headRefOid of [undefined, '', 'abc', '--admin']) {+ const result = await runPullRequestAction({+ action: { headRefOid, method: 'squash', type } as GitPullRequestAction,+ number: 42,+ path: '/repo',+ });+ expect(result.success).toBe(false);+ }+ expect(childProcessMocks.execFileAsync).not.toHaveBeenCalled();+ },+ );++ it.each(['merge', 'autoMerge'] as const)(+ 'fails %s when the remote head has moved',+ async (type) => {+ childProcessMocks.execFileAsync.mockImplementation(async (_command, args) => {+ if (args[args.indexOf('--match-head-commit') + 1] !== 'b'.repeat(40)) {+ throw Object.assign(new Error('head changed'), { stderr: 'head changed' });+ }+ return { stdout: '' };+ });+ const result = await runPullRequestAction({+ action: { headRefOid: 'a'.repeat(40), method: 'squash', type },+ number: 42,+ path: '/repo',+ });+ expect(result).toEqual({ error: 'head changed', success: false });+ },+ );+});++describe('getPullRequestDetail', () => {+ beforeEach(() => {+ childProcessMocks.execFileAsync.mockReset();+ });++ it('reports gh-missing when the gh CLI is unavailable', async () => {+ childProcessMocks.execFileAsync.mockRejectedValue(+ Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' }),+ );++ expect(await getPullRequestDetail({ number: 42, path: '/repo' })).toEqual({+ detail: null,+ status: 'gh-missing',+ });+ });++ it('reports error on any other gh failure', async () => {+ childProcessMocks.execFileAsync.mockRejectedValue(+ Object.assign(new Error('boom'), { stderr: 'boom' }),+ );++ expect(await getPullRequestDetail({ number: 42, path: '/repo' })).toEqual({+ detail: null,+ status: 'error',+ });+ });+});++describe('incremental pull request reads', () => {+ it('returns core data while the activity request is still pending', async () => {+ let releaseActivity!: (value: { stdout: string }) => void;+ const raw = {+ number: 42,+ title: 'Ready first',+ url: 'https://github.com/test/repo/pull/42',+ state: 'OPEN',+ headRefOid: 'a'.repeat(40),+ baseRefName: 'main',+ headRefName: 'feature',+ additions: 2,+ deletions: 1,+ changedFiles: 1,+ };+ childProcessMocks.execFileAsync.mockImplementation(async (_cmd, args) => {+ const fields = args[args.indexOf('--json') + 1].split(',');+ if (fields.includes('comments'))+ return new Promise<{ stdout: string }>((resolve) => {+ releaseActivity = resolve;+ });+ return { stdout: JSON.stringify(raw) };+ });+ const core = await getPullRequestDetail({ coreOnly: true, number: 42, path: '/repo' });+ expect(core.detail).toMatchObject({+ title: 'Ready first',+ comments: [],+ viewerCanWrite: false,+ });+ const activity = getPullRequestActivity({ number: 42, path: '/repo' });+ releaseActivity({+ stdout: JSON.stringify({+ comments: [+ { id: 'c1', author: { login: 'reviewer' }, body: 'Arrived later', createdAt: 'now' },+ ],+ }),+ });+ expect(await activity).toMatchObject({+ comments: [{ body: 'Arrived later', author: 'reviewer' }],+ commits: [],+ reviews: [],+ });+ });++ it('propagates activity failures instead of reporting an empty timeline', async () => {+ childProcessMocks.execFileAsync.mockRejectedValue(new Error('offline'));+ await expect(getPullRequestActivity({ number: 42, path: '/repo' })).rejects.toThrow('offline');+ });+});diff --git a/packages/local-file-shell/src/git/index.ts b/packages/local-file-shell/src/git/index.tsindex ec6b6d43237..dc82eb35276 100644--- a/packages/local-file-shell/src/git/index.ts+++ b/packages/local-file-shell/src/git/index.ts@@ -1,5 +1,6 @@export * from './branches';export * from './info';+export * from './pullRequest';export * from './repoType';export * from './types';export * from './upstream';diff --git a/packages/local-file-shell/src/git/pullRequest.ts b/packages/local-file-shell/src/git/pullRequest.tsnew file mode 100644index 00000000000..3d540ee126a--- /dev/null+++ b/packages/local-file-shell/src/git/pullRequest.ts@@ -0,0 +1,446 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++import { createLogger } from '../logger';+import type {+ GitPullRequestAction,+ GitPullRequestActionResult,+ GitPullRequestActivity,+ GitPullRequestCheck,+ GitPullRequestDetail,+ GitPullRequestDetailResult,+ GitPullRequestMergeContext,+} from './types';++const log = createLogger('local-file-shell:git');+const execFileAsync = promisify(execFile);++const GITHUB_PULL_REQUEST_DETAIL_FIELDS =+ 'number,title,body,state,isDraft,isCrossRepository,mergedAt,mergeable,mergeStateStatus,reviewDecision,autoMergeRequest,baseRefName,headRefName,headRefOid,url,author,additions,deletions,changedFiles,commits,comments,reviews,statusCheckRollup';++type GithubPullRequestAuthor = { login?: string | null } | null;++type GithubPullRequestCommit = {+ authors?: { login?: string | null }[] | null;+ committedDate?: string | null;+ messageHeadline?: string | null;+ oid: string;+};++type GithubPullRequestComment = {+ author?: GithubPullRequestAuthor;+ body?: string | null;+ createdAt?: string | null;+ id: string;+};++type GithubPullRequestReview = {+ author?: GithubPullRequestAuthor;+ state: string;+ submittedAt?: string | null;+};++type GithubStatusCheckRollupNode = {+ completedAt?: string | null;+ conclusion?: string | null;+ context?: string | null;+ createdAt?: string | null;+ detailsUrl?: string | null;+ name?: string | null;+ startedAt?: string | null;+ state?: string | null;+ status?: string | null;+ targetUrl?: string | null;+};++type GithubPullRequestDetailPayload = {+ additions: number;+ author?: GithubPullRequestAuthor;+ autoMergeRequest?: { mergeMethod?: string | null } | null;+ baseRefName: string;+ body?: string | null;+ changedFiles: number;+ comments?: GithubPullRequestComment[] | null;+ commits?: GithubPullRequestCommit[] | null;+ deletions: number;+ headRefName: string;+ headRefOid: string;+ isCrossRepository?: boolean;+ isDraft?: boolean;+ mergeable?: string | null;+ mergedAt?: string | null;+ mergeStateStatus?: string | null;+ number: number;+ reviewDecision?: string | null;+ reviews?: GithubPullRequestReview[] | null;+ state: string;+ statusCheckRollup?: GithubStatusCheckRollupNode[] | null;+ title: string;+ url: string;+};++export type GithubRepoInfo = { name: string; owner: string };++const failureConclusions = new Set([+ 'action_required',+ 'cancelled',+ 'failure',+ 'startup_failure',+ 'timed_out',+]);+const successConclusions = new Set(['neutral', 'skipped', 'success']);++const toLowerOrUndefined = (value?: string | null) => value?.toLowerCase();++const normalizeCheckStatus = (node: GithubStatusCheckRollupNode): GitPullRequestCheck['status'] => {+ const state = toLowerOrUndefined(node.state);+ if (state) {+ if (state === 'success') return 'success';+ if (state === 'failure' || state === 'error') return 'failure';+ return 'pending';+ }++ const status = toLowerOrUndefined(node.status);+ if (status && status !== 'completed') return 'pending';++ const conclusion = toLowerOrUndefined(node.conclusion);+ if (conclusion === 'skipped') return 'skipped';+ if (conclusion === 'cancelled') return 'cancelled';+ if (conclusion && successConclusions.has(conclusion))+ return conclusion === 'neutral' ? 'neutral' : 'success';+ if (conclusion && failureConclusions.has(conclusion)) return 'failure';+ return 'pending';+};++const normalizeCheck = (node: GithubStatusCheckRollupNode): GitPullRequestCheck => {+ const name = node.name ?? node.context ?? '';+ const detailsUrl = node.detailsUrl ?? node.targetUrl ?? undefined;+ const startedAt = node.startedAt ?? node.createdAt ?? undefined;++ return {+ ...(node.completedAt ? { completedAt: node.completedAt } : {}),+ ...(detailsUrl ? { detailsUrl } : {}),+ name,+ required: false,+ ...(startedAt ? { startedAt } : {}),+ status: normalizeCheckStatus(node),+ };+};++const toMergeMethod = (raw?: string | null): 'merge' | 'rebase' | 'squash' | undefined => {+ const lower = toLowerOrUndefined(raw);+ if (lower === 'merge' || lower === 'rebase' || lower === 'squash') return lower;+ return undefined;+};++export const repoFromPullRequestUrl = (url: string): GithubRepoInfo => {+ const match = /github\.com\/([^/]+)\/([^/]+)\/pull\//.exec(url ?? '');+ return { name: match?.[2] ?? '', owner: match?.[1] ?? '' };+};++const normalizePullRequestActivity = (+ raw: Pick<GithubPullRequestDetailPayload, 'comments' | 'commits' | 'reviews'>,+): GitPullRequestActivity => ({+ comments: (raw.comments ?? []).map((comment) => ({+ author: comment.author?.login ?? '',+ body: comment.body ?? '',+ createdAt: comment.createdAt ?? '',+ id: comment.id,+ })),+ commits: (raw.commits ?? []).map((commit) => ({+ author: commit.authors?.[0]?.login ?? '',+ committedAt: commit.committedDate ?? '',+ message: commit.messageHeadline ?? '',+ sha: commit.oid,+ })),+ reviews: (raw.reviews ?? []).map((review) => ({+ author: review.author?.login ?? '',+ state: review.state as GitPullRequestDetail['reviews'][number]['state'],+ submittedAt: review.submittedAt ?? '',+ })),+});++export const getPullRequestActivity = async (payload: {+ number: number;+ path: string;+}): Promise<GitPullRequestActivity> => {+ const { stdout } = await execFileAsync(+ 'gh',+ ['pr', 'view', String(payload.number), '--json', 'comments,commits,reviews'],+ { cwd: payload.path, timeout: 8000 },+ );+ return normalizePullRequestActivity(JSON.parse(stdout));+};++export const normalizePullRequestDetail = (+ raw: GithubPullRequestDetailPayload,+ repo: GithubRepoInfo,+): GitPullRequestDetail => {+ const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod);++ return {+ additions: raw.additions,+ author: raw.author?.login ?? '',+ autoMerge: autoMergeMethod ? { method: autoMergeMethod } : null,+ baseBehindBy: 0,+ baseRefName: raw.baseRefName,+ body: raw.body ?? '',+ changedFiles: raw.changedFiles,+ checks: (raw.statusCheckRollup ?? []).map(normalizeCheck),+ ...normalizePullRequestActivity(raw),+ deletions: raw.deletions,+ headRefName: raw.headRefName,+ headRefOid: raw.headRefOid,+ isCrossRepository: raw.isCrossRepository ?? false,+ isDraft: raw.isDraft ?? false,+ mergeable: (raw.mergeable as GitPullRequestDetail['mergeable']) ?? 'UNKNOWN',+ ...(raw.mergedAt ? { mergedAt: raw.mergedAt } : {}),+ mergeStateStatus:+ (raw.mergeStateStatus as GitPullRequestDetail['mergeStateStatus']) ?? 'UNKNOWN',+ number: raw.number,+ repo: { name: repo.name, owner: repo.owner },+ reviewDecision: (raw.reviewDecision || null) as GitPullRequestDetail['reviewDecision'],+ state: raw.mergedAt ? 'merged' : toLowerOrUndefined(raw.state) === 'closed' ? 'closed' : 'open',+ title: raw.title,+ url: raw.url,+ viewerCanBypass: false,+ viewerCanWrite: false,+ };+};++const MERGE_CONTEXT_GRAPHQL = `+query($owner: String!, $name: String!, $number: Int!) {+ repository(owner: $owner, name: $name) {+ viewerPermission+ pullRequest(number: $number) {+ baseRef {+ branchProtectionRule { requiredStatusCheckContexts }+ }+ }+ }+}`.trim();++type MergeContextPayload = {+ data?: {+ repository?: {+ pullRequest?: {+ baseRef?: {+ branchProtectionRule?: { requiredStatusCheckContexts?: string[] | null } | null;+ } | null;+ } | null;+ viewerPermission?: string | null;+ } | null;+ };+};++const EMPTY_MERGE_CONTEXT: GitPullRequestMergeContext = {+ baseBehindBy: 0,+ requiredChecks: [],+ viewerCanBypass: false,+ viewerCanWrite: false,+};++export const normalizeMergeContext = (+ payload: MergeContextPayload,+ baseBehindBy: number,+): GitPullRequestMergeContext => {+ const repository = payload.data?.repository;+ const viewerPermission = repository?.viewerPermission ?? '';+ return {+ baseBehindBy,+ requiredChecks:+ repository?.pullRequest?.baseRef?.branchProtectionRule?.requiredStatusCheckContexts ?? [],+ viewerCanBypass: viewerPermission === 'ADMIN',+ viewerCanWrite:+ viewerPermission === 'ADMIN' ||+ viewerPermission === 'MAINTAIN' ||+ viewerPermission === 'WRITE',+ };+};++export const getPullRequestMergeContext = async (payload: {+ baseRefName: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: GithubRepoInfo;+}): Promise<GitPullRequestMergeContext> => {+ const { path: dirPath, number, repo, baseRefName, headRefOid } = payload;+ assertBranchName(baseRefName);+ if (!/^[a-f\d]{40}$/i.test(headRefOid)) return EMPTY_MERGE_CONTEXT;+ const exec = (args: string[]) => execFileAsync('gh', args, { cwd: dirPath, timeout: 8000 });++ const [graphql, compare] = await Promise.allSettled([+ exec([+ 'api',+ 'graphql',+ '-F',+ `owner=${repo.owner}`,+ '-F',+ `name=${repo.name}`,+ '-F',+ `number=${number}`,+ '-f',+ `query=${MERGE_CONTEXT_GRAPHQL}`,+ ]),+ exec([+ 'api',+ `repos/${repo.owner}/${repo.name}/compare/${baseRefName}...${headRefOid}`,+ '--jq',+ '.behind_by',+ ]),+ ]);++ if (graphql.status === 'rejected')+ log.debug('[getPullRequestMergeContext] failed', { number, stderr: graphql.reason?.stderr });+ const parsed =+ graphql.status === 'fulfilled'+ ? (JSON.parse(graphql.value.stdout.trim() || '{}') as MergeContextPayload)+ : {};+ const baseBehindBy =+ compare.status === 'fulfilled' ? Number(compare.value.stdout.trim()) || 0 : 0;+ return normalizeMergeContext(parsed, baseBehindBy);+};++const VALID_BRANCH_NAME = /^[\w./-]+$/;++const assertBranchName = (name: string) => {+ if (!VALID_BRANCH_NAME.test(name) || name.split('/').includes('..'))+ throw new Error('Invalid branch name');+};++const isGhMissing = (error: any): boolean => {+ const code = error?.code;+ const stderr: string = error?.stderr ?? '';+ return code === 'ENOENT' || /auth\s+login|not\s+logged\s+in|authentication/i.test(stderr);+};++export const getPullRequestDetail = async (payload: {+ coreOnly?: boolean;+ number: number;+ path: string;+}): Promise<GitPullRequestDetailResult> => {+ const { path: dirPath, number } = payload;++ try {+ const { stdout } = await execFileAsync(+ 'gh',+ [+ 'pr',+ 'view',+ String(number),+ '--json',+ payload.coreOnly+ ? GITHUB_PULL_REQUEST_DETAIL_FIELDS.split(',')+ .filter((field) => !['comments', 'commits', 'reviews'].includes(field))+ .join(',')+ : GITHUB_PULL_REQUEST_DETAIL_FIELDS,+ ],+ { cwd: dirPath, timeout: 8000 },+ );++ const raw = JSON.parse(stdout.trim() || '{}') as GithubPullRequestDetailPayload;++ return {+ detail: normalizePullRequestDetail(raw, repoFromPullRequestUrl(raw.url)),+ status: 'ok',+ };+ } catch (error: any) {+ if (isGhMissing(error)) return { detail: null, status: 'gh-missing' };+ log.debug('[getPullRequestDetail] failed', {+ code: error?.code,+ number,+ stderr: error?.stderr,+ });+ return { detail: null, status: 'error' };+ }+};++export const pullRequestActionArgs = (number: number, action: GitPullRequestAction): string[][] => {+ const n = String(number);+ if (+ (action.type === 'merge' || action.type === 'autoMerge') &&+ !/^[a-f\d]{40}$/i.test(action.headRefOid ?? '')+ )+ throw new Error('A valid pull request head commit is required');++ switch (action.type) {+ case 'merge': {+ const argv = [+ 'pr',+ 'merge',+ n,+ `--${action.method}`,+ '--match-head-commit',+ action.headRefOid,+ ];+ if (action.admin) argv.push('--admin');+ if (action.deleteBranch) argv.push('--delete-branch');+ return [argv];+ }+ case 'autoMerge': {+ return [+ [+ 'pr',+ 'merge',+ n,+ '--auto',+ `--${action.method}`,+ '--match-head-commit',+ action.headRefOid,+ ],+ ];+ }+ case 'disableAutoMerge': {+ return [['pr', 'merge', n, '--disable-auto']];+ }+ case 'updateBranch': {+ return [+ action.method === 'rebase'+ ? ['pr', 'update-branch', n, '--rebase']+ : ['pr', 'update-branch', n],+ ];+ }+ case 'ready': {+ return [['pr', 'ready', n]];+ }+ case 'comment': {+ return [['pr', 'comment', n, '--body', action.body]];+ }+ case 'close': {+ return [['pr', 'close', n]];+ }+ case 'reopen': {+ return [['pr', 'reopen', n]];+ }+ case 'deleteBranch': {+ assertBranchName(action.head);+ return [['api', '-X', 'DELETE', `repos/{owner}/{repo}/git/refs/heads/${action.head}`]];+ }+ case 'changeBase': {+ assertBranchName(action.base);+ return [['pr', 'edit', n, '--base', action.base]];+ }+ }+};++export const runPullRequestAction = async (payload: {+ action: GitPullRequestAction;+ number: number;+ path: string;+}): Promise<GitPullRequestActionResult> => {+ const { path: dirPath, number, action } = payload;++ try {+ for (const argv of pullRequestActionArgs(number, action)) {+ await execFileAsync('gh', argv, { cwd: dirPath, timeout: 60_000 });+ }+ return { success: true };+ } catch (error: any) {+ log.debug('[runPullRequestAction] failed', { action: action.type, code: error?.code, number });+ return {+ error: (error?.stderr as string)?.trim() || error?.message || 'unknown error',+ success: false,+ };+ }+};diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.tsindex eddc932c6f5..0f1442f40ec 100644--- a/packages/local-file-shell/src/git/types.ts+++ b/packages/local-file-shell/src/git/types.ts@@ -53,6 +53,111 @@ export interface GitLinkedPullRequestResult {upstream?: GitUpstreamRef;}+export interface GitPullRequestCheck {+ completedAt?: string;+ detailsUrl?: string;+ name: string;+ required: boolean;+ startedAt?: string;+ status: 'cancelled' | 'failure' | 'neutral' | 'pending' | 'skipped' | 'success';+}++export interface GitPullRequestComment {+ author: string;+ body: string;+ createdAt: string;+ id: string;+}++export interface GitPullRequestReview {+ author: string;+ state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'DISMISSED' | 'PENDING';+ submittedAt: string;+}++export interface GitPullRequestCommit {+ author: string;+ committedAt: string;+ message: string;+ sha: string;+}++export interface GitPullRequestDetail {+ additions: number;+ author: string;+ autoMerge?: { method: 'merge' | 'rebase' | 'squash' } | null;+ baseBehindBy: number;+ baseRefName: string;+ body: string;+ changedFiles: number;+ checks: GitPullRequestCheck[];+ comments: GitPullRequestComment[];+ commits: GitPullRequestCommit[];+ deletions: number;+ headRefName: string;+ headRefOid: string;+ isCrossRepository: boolean;+ isDraft: boolean;+ mergeable: 'CONFLICTING' | 'MERGEABLE' | 'UNKNOWN';+ mergedAt?: string;+ mergeStateStatus:+ 'BEHIND' | 'BLOCKED' | 'CLEAN' | 'DIRTY' | 'DRAFT' | 'HAS_HOOKS' | 'UNKNOWN' | 'UNSTABLE';+ number: number;+ repo: { name: string; owner: string };+ reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null;+ reviews: GitPullRequestReview[];+ state: 'closed' | 'merged' | 'open';+ title: string;+ url: string;+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++export type GitPullRequestActivity = Pick<GitPullRequestDetail, 'comments' | 'commits' | 'reviews'>;++export interface GitPullRequestDetailResult {+ detail: GitPullRequestDetail | null;+ status: GitLinkedPullRequestLookupStatus;+}++export type GitPullRequestMergeMethod = 'merge' | 'rebase' | 'squash';++/**+ * Slow, permission-dependent merge context resolved separately from the PR+ * detail so the pane can paint before branch protection / compare calls land.+ */+export interface GitPullRequestMergeContext {+ /** Commits the base branch has that the PR head does not. */+ baseBehindBy: number;+ /** Status-check contexts required by branch protection on the base branch. */+ requiredChecks: string[];+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++export type GitPullRequestAction =+ | {+ admin?: boolean;+ deleteBranch?: boolean;+ headRefOid: string;+ method: GitPullRequestMergeMethod;+ type: 'merge';+ }+ | { headRefOid: string; method: GitPullRequestMergeMethod; type: 'autoMerge' }+ | { type: 'disableAutoMerge' }+ | { method: 'merge' | 'rebase'; type: 'updateBranch' }+ | { type: 'ready' }+ | { body: string; type: 'comment' }+ | { type: 'close' }+ | { type: 'reopen' }+ | { head: string; type: 'deleteBranch' }+ | { base: string; type: 'changeBase' };++export interface GitPullRequestActionResult {+ error?: string;+ success: boolean;+}+export interface GitWorkingTreeStatus {added: number;clean: boolean;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 04f92dd91e5..e88184ce7a7 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2876,6 +2876,106 @@ export default {'workingPanel.files.views.changes': 'Git Changes','workingPanel.files.views.project': 'Project','workingPanel.files.views.title': 'File View',+ 'workingPanel.pr.action.arming': 'Arming auto-merge…',+ 'workingPanel.pr.action.autoMerge': 'Auto-merge when ready',+ 'workingPanel.pr.action.bypassSuffix': 'bypass rules',+ 'workingPanel.pr.action.calculating': 'Calculating…',+ 'workingPanel.pr.action.conflicting': 'Resolve conflicts to merge',+ 'workingPanel.pr.action.deleteBranch': 'Delete branch',+ 'workingPanel.pr.action.disableAutoMerge': 'Disable',+ 'workingPanel.pr.action.merging': 'Merging…',+ 'workingPanel.pr.action.push_one': 'Push {{count}} commit',+ 'workingPanel.pr.action.push_other': 'Push {{count}} commits',+ 'workingPanel.pr.action.pushing': 'Pushing…',+ 'workingPanel.pr.action.ready': 'Mark ready for review',+ 'workingPanel.pr.action.readying': 'Marking ready…',+ 'workingPanel.pr.action.reopen': 'Reopen pull request',+ 'workingPanel.pr.action.updateBranch': 'Update branch',+ 'workingPanel.pr.action.updateBranch.merge': 'Update with merge commit',+ 'workingPanel.pr.action.updateBranch.rebase': 'Update with rebase',+ 'workingPanel.pr.action.updating': 'Updating branch…',+ 'workingPanel.pr.action.waiting': 'Waiting for checks…',+ 'workingPanel.pr.activity.approved': 'approved',+ 'workingPanel.pr.activity.changesRequested': 'requested changes',+ 'workingPanel.pr.activity.commented': 'reviewed',+ 'workingPanel.pr.activity.committed': 'committed',+ 'workingPanel.pr.activity.dismissed': 'review dismissed',+ 'workingPanel.pr.bypass': 'Merge without waiting for requirements',+ 'workingPanel.pr.check.optional': 'optional',+ 'workingPanel.pr.check.queued': 'queued',+ 'workingPanel.pr.checks.failing_one': '{{count}} failing',+ 'workingPanel.pr.checks.failing_other': '{{count}} failing',+ 'workingPanel.pr.checks.running_one': '{{count}} running',+ 'workingPanel.pr.checks.running_other': '{{count}} running',+ 'workingPanel.pr.composer.placeholder': 'Write a comment…',+ 'workingPanel.pr.composer.submit': 'Comment',+ 'workingPanel.pr.dismiss': 'Dismiss',+ 'workingPanel.pr.error.load': 'Could not load this pull request',+ 'workingPanel.pr.files.openReview': 'Open diff in Review',+ 'workingPanel.pr.ghMissing.desc': 'Install gh and run gh auth login to load pull requests here.',+ 'workingPanel.pr.ghMissing.open': 'Open in Browser',+ 'workingPanel.pr.ghMissing.retry': 'Check again',+ 'workingPanel.pr.ghMissing.title': "GitHub CLI isn't set up on this device",+ 'workingPanel.pr.header.changeBase': 'Change base branch',+ 'workingPanel.pr.header.commits_one': '{{count}} commit',+ 'workingPanel.pr.header.commits_other': '{{count}} commits',+ 'workingPanel.pr.hint.autoMerge':+ 'Will {{method}} once checks pass. Cancels on new commits or a changes-requested review.',+ 'workingPanel.pr.hint.blocked':+ 'Push a fix or wait for requirements; this refreshes automatically.',+ 'workingPanel.pr.hint.bypass': 'Bypass is recorded on GitHub and visible in the audit log.',+ 'workingPanel.pr.hint.calculating':+ 'GitHub is recomputing after the last push; usually a few seconds.',+ 'workingPanel.pr.hint.merge_one': 'Merges {{count}} commit into {{base}}.',+ 'workingPanel.pr.hint.merge_other': 'Merges {{count}} commits into {{base}}.',+ 'workingPanel.pr.hint.merged': '{{head}} is safe to delete.',+ 'workingPanel.pr.hint.readOnly': 'Only maintainers of {{repo}} can merge this pull request.',+ 'workingPanel.pr.menu.close': 'Close pull request',+ 'workingPanel.pr.menu.copied': 'Link copied',+ 'workingPanel.pr.menu.copyLink': 'Copy link',+ 'workingPanel.pr.menu.openOnGithub': 'Open on GitHub',+ 'workingPanel.pr.menu.reopen': 'Reopen pull request',+ 'workingPanel.pr.method.merge': 'Create a merge commit',+ 'workingPanel.pr.method.merge.desc': 'Keep all commits and add a merge commit on {{base}}.',+ 'workingPanel.pr.method.rebase': 'Rebase and merge',+ 'workingPanel.pr.method.rebase.desc': 'Replay the commits onto {{base}}.',+ 'workingPanel.pr.method.squash': 'Squash and merge',+ 'workingPanel.pr.method.squash.desc': 'Combine the commits into one on {{base}}.',+ 'workingPanel.pr.reason.behind': 'Branch is behind {{base}}',+ 'workingPanel.pr.reason.changesRequested': 'Changes requested by {{authors}}',+ 'workingPanel.pr.reason.checksFailing_one': '{{count}} required check failing',+ 'workingPanel.pr.reason.checksFailing_other': '{{count}} required checks failing',+ 'workingPanel.pr.reason.checksPending': 'Checks running',+ 'workingPanel.pr.reason.conflicts': 'Conflicts with {{base}}',+ 'workingPanel.pr.reason.localAhead_one': '{{count}} local commit not pushed',+ 'workingPanel.pr.reason.localAhead_other': '{{count}} local commits not pushed',+ 'workingPanel.pr.reason.localDirty_one': '{{count}} uncommitted file',+ 'workingPanel.pr.reason.localDirty_other': '{{count}} uncommitted files',+ 'workingPanel.pr.reason.optionalFailing_one': '{{count}} optional check failing',+ 'workingPanel.pr.reason.optionalFailing_other': '{{count}} optional checks failing',+ 'workingPanel.pr.reason.reviewRequired': 'Review required',+ 'workingPanel.pr.reason.rules': 'Blocked by branch rules',+ 'workingPanel.pr.status.autoMerge': 'Auto-merge enabled ({{method}})',+ 'workingPanel.pr.status.blocked': 'Merging is blocked',+ 'workingPanel.pr.status.bypass': 'Bypassing branch protection',+ 'workingPanel.pr.status.calculating': 'Checking mergeability…',+ 'workingPanel.pr.status.closed': 'Closed without merging',+ 'workingPanel.pr.status.conflicts': 'This branch has conflicts with {{base}}',+ 'workingPanel.pr.status.draft': 'Still a draft',+ 'workingPanel.pr.status.error': 'Merge failed: {{message}}',+ 'workingPanel.pr.status.merged': 'Merged',+ 'workingPanel.pr.status.ready': 'Ready to merge',+ 'workingPanel.pr.status.unstable': 'Some checks were not successful',+ 'workingPanel.pr.status.waiting': 'Waiting for checks',+ 'workingPanel.pr.section.activity': 'Activity',+ 'workingPanel.pr.section.checks': 'Checks',+ 'workingPanel.pr.section.commits': 'Commits',+ 'workingPanel.pr.section.description': 'Description',+ 'workingPanel.pr.section.files': 'Files changed',+ 'workingPanel.pr.state.closed': 'Closed',+ 'workingPanel.pr.state.draft': 'Draft',+ 'workingPanel.pr.state.merged': 'Merged',+ 'workingPanel.pr.state.open': 'Open','workingPanel.review.baseRef.default': 'default','workingPanel.review.baseRef.loading': 'Loading branches…','workingPanel.review.baseRef.reset': 'Reset to default branch',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 28d1f3919aa..633362ac6e0 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -444,6 +444,116 @@ export interface DeviceGitLinkedPullRequestResult {upstream?: DeviceGitUpstreamRef;}+/** One CI check on a pull request, from `statusCheckRollup` (CheckRun or StatusContext). */+export interface DeviceGitPullRequestCheck {+ completedAt?: string;+ detailsUrl?: string;+ name: string;+ required: boolean;+ startedAt?: string;+ status: 'cancelled' | 'failure' | 'neutral' | 'pending' | 'skipped' | 'success';+}++export interface DeviceGitPullRequestComment {+ author: string;+ body: string;+ createdAt: string;+ id: string;+}++export interface DeviceGitPullRequestReview {+ author: string;+ state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'DISMISSED' | 'PENDING';+ submittedAt: string;+}++export interface DeviceGitPullRequestCommit {+ author: string;+ committedAt: string;+ message: string;+ sha: string;+}++/**+ * Full pull request detail returned by the `getPullRequestDetail` device RPC.+ * Backs the Working Sidebar's Pull Request tab.+ */+export interface DeviceGitPullRequestDetail {+ additions: number;+ author: string;+ autoMerge?: { method: 'merge' | 'rebase' | 'squash' } | null;+ baseBehindBy: number;+ baseRefName: string;+ body: string;+ changedFiles: number;+ checks: DeviceGitPullRequestCheck[];+ comments: DeviceGitPullRequestComment[];+ commits: DeviceGitPullRequestCommit[];+ deletions: number;+ headRefName: string;+ headRefOid: string;+ isCrossRepository: boolean;+ isDraft: boolean;+ mergeable: 'CONFLICTING' | 'MERGEABLE' | 'UNKNOWN';+ mergedAt?: string;+ mergeStateStatus:+ 'BEHIND' | 'BLOCKED' | 'CLEAN' | 'DIRTY' | 'DRAFT' | 'HAS_HOOKS' | 'UNKNOWN' | 'UNSTABLE';+ number: number;+ repo: { name: string; owner: string };+ reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null;+ reviews: DeviceGitPullRequestReview[];+ state: 'closed' | 'merged' | 'open';+ title: string;+ url: string;+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++/** Result of the `getPullRequestDetail` device RPC. */+export type DeviceGitPullRequestActivity = Pick<+ DeviceGitPullRequestDetail,+ 'comments' | 'commits' | 'reviews'+>;++export interface DeviceGitPullRequestDetailResult {+ detail: DeviceGitPullRequestDetail | null;+ status: DeviceGitLinkedPullRequestLookupStatus;+}++export type DeviceGitPullRequestMergeMethod = 'merge' | 'rebase' | 'squash';++/** Result of the `getPullRequestMergeContext` device RPC. */+export interface DeviceGitPullRequestMergeContext {+ baseBehindBy: number;+ requiredChecks: string[];+ viewerCanBypass: boolean;+ viewerCanWrite: boolean;+}++/** One `gh pr` mutation dispatched by the `runPullRequestAction` device RPC. */+export type DeviceGitPullRequestAction =+ | {+ admin?: boolean;+ deleteBranch?: boolean;+ headRefOid: string;+ method: DeviceGitPullRequestMergeMethod;+ type: 'merge';+ }+ | { headRefOid: string; method: DeviceGitPullRequestMergeMethod; type: 'autoMerge' }+ | { type: 'disableAutoMerge' }+ | { method: 'merge' | 'rebase'; type: 'updateBranch' }+ | { type: 'ready' }+ | { body: string; type: 'comment' }+ | { type: 'close' }+ | { type: 'reopen' }+ | { head: string; type: 'deleteBranch' }+ | { base: string; type: 'changeBase' };++export interface DeviceGitPullRequestActionResult {+ error?: string;+ success: boolean;+}+/*** Working-tree dirty-file counts for a working directory, returned by the* `getGitWorkingTreeStatus` device RPC. Mirrors the desktop shape.diff --git a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts b/src/features/AgentSidebar/Topic/List/Item/metaCardData.tsindex 798f401c19d..08bca4a76bf 100644--- a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts+++ b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts@@ -31,7 +31,9 @@ export type PullRequestState = 'open' | 'merged' | 'closed';* Resolve a GitHub PR's lifecycle state. GitHub's `state` is only open|closed;* "merged" is a closed PR carrying a `mergedAt`, so check that first.*/-export const getPullRequestState = (pr: DeviceGitLinkedPullRequest): PullRequestState => {+export const getPullRequestState = (+ pr: Pick<DeviceGitLinkedPullRequest, 'mergedAt' | 'state'>,+): PullRequestState => {if (pr.mergedAt || pr.state === 'merged') return 'merged';if (pr.state === 'closed') return 'closed';return 'open';@@ -39,7 +41,7 @@ export const getPullRequestState = (pr: DeviceGitLinkedPullRequest): PullRequest// GitHub merged-PR purple. Kept as a constant since antd's token set has no// semantic "merged" color; the green (success) / red (error) come from tokens.-const MERGED_PURPLE = '#8957e5';+export const MERGED_PURPLE = '#8957e5';export interface PullRequestStateVisual {color: string;diff --git a/src/features/Conversation/WorkingSidebar/Overview/OverviewRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/OverviewRow.tsxindex dd2fd930691..ba9fead4eeb 100644--- a/src/features/Conversation/WorkingSidebar/Overview/OverviewRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/OverviewRow.tsx@@ -92,6 +92,7 @@ export interface OverviewRowProps {iconSize?: number;interactive?: boolean;onClick?: () => void;+ spin?: boolean;title?: string;trailing?: ReactNode;value: ReactNode;@@ -107,6 +108,7 @@ export const OverviewRow = memo<OverviewRowProps>(iconSize = 16,interactive,onClick,+ spin,title,trailing,value,@@ -125,6 +127,7 @@ export const OverviewRow = memo<OverviewRowProps>(className={rowStyles.icon}icon={icon!}size={iconSize}+ spin={spin}style={iconColor ? { color: iconColor } : undefined}/>)}diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 947227b978e..326b6f2b221 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -48,8 +48,9 @@ import ProgressSection from '../ProgressSection';import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';import OverviewHeader from './OverviewHeader';import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';+import { sectionStyles } from './sectionStyles';-const styles = createStaticStyles(({ css, cssVar }) => ({+const styles = createStaticStyles(({ css }) => ({body: css`overflow-y: auto;`,@@ -57,43 +58,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({padding-block: 28px 30px;padding-inline: 20px;`,- pill: css`- display: inline-flex;- gap: 4px;- align-items: center;-- height: 20px;- padding-inline: 7px;- border-radius: 6px;-- font-size: 11.5px;- font-weight: 500;- line-height: 20px;- `,- section: css`- flex-shrink: 0;- padding-block: 8px;- padding-inline: 8px;-- & + & {- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- }- `,- sectionHeader: css`- padding-block: 0 4px;- padding-inline: 8px;- `,- sectionTitle: css`- font-size: 10.5px;- font-weight: 600;- color: ${cssVar.colorTextTertiary};- text-transform: uppercase;- letter-spacing: 0.08em;- `,- skeleton: css`- padding-block: 4px;- padding-inline: 8px;- `,}));interface OverviewProps {@@ -102,6 +66,7 @@ interface OverviewProps {deviceId?: string;environmentAvailable: boolean;onOpenTab: (tab: string) => void;+ prAvailable?: boolean;repoType?: string;sourcePath?: string;workingDirectory?: string;@@ -116,6 +81,7 @@ const Overview = memo<OverviewProps>(deviceId,environmentAvailable,onOpenTab,+ prAvailable,repoType,sourcePath,workingDirectory,@@ -349,7 +315,6 @@ const Overview = memo<OverviewProps>(<OverviewRowicon={ClipboardListIcon}- value={t('workingPanel.overview.changes')}trailing={changeStats.files > 0 ? (<>@@ -360,6 +325,11 @@ const Overview = memo<OverviewProps>(t('workingPanel.overview.changes.none'))}+ value={+ changeStats.files > 0+ ? t('workingPanel.pr.reason.localDirty', { count: changeStats.files })+ : t('workingPanel.overview.changes')+ }onClick={() => onOpenTab('review')}/>@@ -371,7 +341,7 @@ const Overview = memo<OverviewProps>(iconColor={prVisual.color}trailing={<span- className={styles.pill}+ className={sectionStyles.pill}style={{ background: `color-mix(in srgb, 12%, transparent)`, color: ci.color }}><Icon icon={ci.icon} size={12} />@@ -389,9 +359,11 @@ const Overview = memo<OverviewProps>(</>}onClick={- pullRequest.url- ? () => void electronSystemService.openExternalLink(pullRequest.url)- : undefined+ prAvailable+ ? () => onOpenTab('pr')+ : pullRequest.url+ ? () => void electronSystemService.openExternalLink(pullRequest.url)+ : undefined}/></div>@@ -402,7 +374,7 @@ const Overview = memo<OverviewProps>(const workspaceSection = repoType ? (isGitLoading ? (- <div className={styles.skeleton}>+ <div className={sectionStyles.skeleton}><Skeleton.Text rows={3} /></div>) : gitError ? (@@ -445,30 +417,32 @@ const Overview = memo<OverviewProps>(repoType={repoType}onClick={() => onOpenTab('files')}/>- <Flexbox className={styles.section}>{workspaceSection}</Flexbox>+ <Flexbox className={sectionStyles.section}>{workspaceSection}</Flexbox></>)}{environmentAvailable && !workingDirectory && (<Empty- className={cx(styles.section, styles.emptyWorkspace)}+ className={cx(sectionStyles.section, styles.emptyWorkspace)}description={t('workingPanel.overview.workspace.emptyDesc')}icon={LaptopIcon}title={t('workingPanel.overview.workspace.empty')}/>)}- <ProgressSection className={styles.section} />+ <ProgressSection className={sectionStyles.section} />{visibleWorks.length > 0 && (- <Flexbox className={styles.section}>+ <Flexbox className={sectionStyles.section}><Flexboxhorizontalalign={'center'}- className={styles.sectionHeader}+ className={sectionStyles.sectionHeader}justify={'space-between'}>- <span className={styles.sectionTitle}>{t('workingPanel.overview.outputs')}</span>+ <span className={sectionStyles.sectionTitle}>+ {t('workingPanel.overview.outputs')}+ </span><Buttonoutdent={'end'}size={'small'}@@ -486,14 +460,14 @@ const Overview = memo<OverviewProps>({!environmentAvailable && !topicId && visibleWorks.length === 0 && (<Empty- className={styles.section}+ className={sectionStyles.section}description={t('workingPanel.overview.empty')}icon={BoxesIcon}title={t('workingPanel.overview.emptyTitle')}/>)}- <Flexbox className={styles.section}>+ <Flexbox className={sectionStyles.section}><OverviewRowweakicon={SkillsIcon}diff --git a/src/features/Conversation/WorkingSidebar/Overview/sectionStyles.ts b/src/features/Conversation/WorkingSidebar/Overview/sectionStyles.tsnew file mode 100644index 00000000000..5c1c9bd3a3a--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/sectionStyles.ts@@ -0,0 +1,55 @@+import { createStaticStyles } from 'antd-style';++export const sectionStyles = createStaticStyles(({ css, cssVar }) => ({+ count: css`+ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ text-transform: none;+ letter-spacing: 0;++ background: ${cssVar.colorFillSecondary};+ `,+ pill: css`+ display: inline-flex;+ gap: 4px;+ align-items: center;++ height: 20px;+ padding-inline: 7px;+ border-radius: 6px;++ font-size: 11.5px;+ font-weight: 500;+ line-height: 20px;+ `,+ section: css`+ flex-shrink: 0;+ padding-block: 8px;+ padding-inline: 8px;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ sectionHeader: css`+ padding-block: 0 4px;+ padding-inline: 8px;+ `,+ sectionTitle: css`+ font-size: 10.5px;+ font-weight: 600;+ color: ${cssVar.colorTextTertiary};+ text-transform: uppercase;+ letter-spacing: 0.08em;+ `,+ skeleton: css`+ padding-block: 4px;+ padding-inline: 8px;+ `,+}));diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsxnew file mode 100644index 00000000000..b93ad42fed0--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/ActivityTimeline.tsx@@ -0,0 +1,252 @@+import type {+ DeviceGitPullRequestAction,+ DeviceGitPullRequestDetail,+ DeviceGitPullRequestReview,+} from '@lobechat/types';+import { Flexbox, Icon, Markdown } from '@lobehub/ui';+import { Avatar, Button, TextArea } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import type { LucideIcon } from 'lucide-react';+import { CheckIcon, CircleSlashIcon, EyeIcon, GitCommitHorizontalIcon, XIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { electronSystemService } from '@/services/electron/system';++import type { Tone } from './mergeDockData';+import { timeAgo, TONE_COLOR, type TranslateKey } from './prVisual';+import type { PullRequestBusy } from './usePullRequestActions';++const styles = createStaticStyles(({ css, cssVar }) => ({+ comment: css`+ padding-block: 6px;+ padding-inline: 8px;+ border-radius: 8px;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ commentBodyWrap: css`+ overflow: hidden;+ min-width: 0;+ padding-inline-start: 26px;+ `,+ commentBody: css`+ overflow: hidden;++ min-width: 0;++ font-size: 13px;+ line-height: 20px;+ overflow-wrap: anywhere;++ table {+ overflow-x: auto;+ display: block;+ max-width: 100%;+ }++ img,+ video {+ max-width: 100%;+ }++ pre {+ overflow-x: auto;+ max-width: 100%;+ }+ `,+ commentHead: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ strong {+ font-weight: 500;+ color: ${cssVar.colorText};+ }+ `,+ composer: css`+ padding-block: 4px 0;+ padding-inline: 8px;+ `,+ event: css`+ min-height: 28px;+ padding-block: 2px;+ padding-inline: 8px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ strong {+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ }++ code {+ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ }+ `,+ sha: css`+ cursor: pointer;+ text-decoration: underline dotted;+ text-underline-offset: 2px;++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+}));++const githubAvatar = (login: string) => `https://github.com/${login}.png?size=36`;++const REVIEW_VISUAL: Record<+ DeviceGitPullRequestReview['state'],+ { icon: LucideIcon; labelKey: string; tone: Tone }+> = {+ APPROVED: { icon: CheckIcon, labelKey: 'workingPanel.pr.activity.approved', tone: 'success' },+ CHANGES_REQUESTED: {+ icon: XIcon,+ labelKey: 'workingPanel.pr.activity.changesRequested',+ tone: 'error',+ },+ COMMENTED: { icon: EyeIcon, labelKey: 'workingPanel.pr.activity.commented', tone: 'neutral' },+ DISMISSED: {+ icon: CircleSlashIcon,+ labelKey: 'workingPanel.pr.activity.dismissed',+ tone: 'neutral',+ },+ PENDING: { icon: EyeIcon, labelKey: 'workingPanel.pr.activity.commented', tone: 'neutral' },+};++type Entry =+ | { at: string; kind: 'comment'; author: string; body: string; id: string }+ | { at: string; kind: 'commit'; author: string; sha: string }+ | { at: string; kind: 'review'; author: string; state: DeviceGitPullRequestReview['state'] };++const buildTimeline = (detail: DeviceGitPullRequestDetail): Entry[] =>+ [+ ...detail.comments.map<Entry>((comment) => ({+ at: comment.createdAt,+ author: comment.author,+ body: comment.body,+ id: comment.id,+ kind: 'comment',+ })),+ ...detail.commits.map<Entry>((commit) => ({+ at: commit.committedAt,+ author: commit.author,+ kind: 'commit',+ sha: commit.sha,+ })),+ ...detail.reviews.map<Entry>((review) => ({+ at: review.submittedAt,+ author: review.author,+ kind: 'review',+ state: review.state,+ })),+ ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));++interface ActivityTimelineProps {+ busy?: PullRequestBusy;+ detail: DeviceGitPullRequestDetail;+ onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;+}++const ActivityTimeline = memo<ActivityTimelineProps>(({ busy, detail, onAction }) => {+ const { t } = useTranslation('chat');+ const tr = t as unknown as TranslateKey;+ const [draft, setDraft] = useState('');+ const timeline = useMemo(() => buildTimeline(detail), [detail]);++ const submit = async () => {+ const body = draft.trim();+ if (!body) return;+ if (await onAction({ body, type: 'comment' })) setDraft('');+ };++ return (+ <>+ {timeline.map((entry) => {+ if (entry.kind === 'comment')+ return (+ <div className={styles.comment} key={entry.id}>+ <Flexbox horizontal align={'center'} className={styles.commentHead} gap={8}>+ <Avatar avatar={githubAvatar(entry.author)} size={18} />+ <strong>{entry.author}</strong>+ <span>{timeAgo(entry.at)}</span>+ </Flexbox>+ <div className={styles.commentBodyWrap}>+ <Markdown allowHtml className={styles.commentBody} fontSize={13} variant={'chat'}>+ {entry.body}+ </Markdown>+ </div>+ </div>+ );+ const visual =+ entry.kind === 'review'+ ? REVIEW_VISUAL[entry.state]+ : {+ icon: GitCommitHorizontalIcon,+ labelKey: 'workingPanel.pr.activity.committed',+ tone: 'neutral' as Tone,+ };+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.event}+ gap={8}+ key={entry.kind === 'commit' ? entry.sha : `review:${entry.author}:${entry.at}`}+ >+ <Icon+ icon={visual.icon}+ size={14}+ style={visual.tone === 'neutral' ? undefined : { color: TONE_COLOR[visual.tone] }}+ />+ <span>+ <strong>{entry.author}</strong> {tr(visual.labelKey)}{' '}+ {entry.kind === 'commit' && (+ <code+ className={styles.sha}+ onClick={() =>+ void electronSystemService.openExternalLink(+ `https://github.com/${detail.repo.owner}/${detail.repo.name}/pull/${detail.number}/commits/${entry.sha}`,+ )+ }+ >+ {entry.sha.slice(0, 7)}+ </code>+ )}{' '}+ · {timeAgo(entry.at)}+ </span>+ </Flexbox>+ );+ })}+ <Flexbox className={styles.composer} gap={6}>+ <TextArea+ autoSize={{ minRows: 1 }}+ placeholder={t('workingPanel.pr.composer.placeholder')}+ value={draft}+ variant={'filled'}+ onChange={(e) => setDraft(e.target.value)}+ />+ <Flexbox horizontal justify={'flex-end'}>+ <Button+ disabled={!draft.trim() || !!busy}+ loading={busy === 'comment'}+ size={'small'}+ onClick={() => void submit()}+ >+ {t('workingPanel.pr.composer.submit')}+ </Button>+ </Flexbox>+ </Flexbox>+ </>+ );+});++ActivityTimeline.displayName = 'PullRequestActivityTimeline';++export default ActivityTimeline;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/ChecksList.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/ChecksList.tsxnew file mode 100644index 00000000000..d76a59f5478--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/ChecksList.tsx@@ -0,0 +1,69 @@+import type { DeviceGitPullRequestCheck } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { ExternalLinkIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { electronSystemService } from '@/services/electron/system';++import { OverviewRow } from '../Overview/OverviewRow';+import { formatCheckDuration, getCheckVisual, TONE_COLOR } from './prVisual';++const styles = createStaticStyles(({ css, cssVar }) => ({+ duration: css`+ font-family: ${cssVar.fontFamilyCode};+ `,+ list: css`+ padding-inline-start: 18px;+ `,+}));++interface ChecksListProps {+ checks: DeviceGitPullRequestCheck[];+}++const ChecksList = memo<ChecksListProps>(({ checks }) => {+ const { t } = useTranslation('chat');+ const hasRequiredCheck = checks.some((check) => check.required);+ return (+ <div className={styles.list}>+ {checks.map((check, index) => {+ const visual = getCheckVisual(check.status);+ const duration =+ check.status === 'pending' && !check.startedAt+ ? t('workingPanel.pr.check.queued')+ : formatCheckDuration(check);+ return (+ <OverviewRow+ weak+ icon={visual.icon}+ iconColor={TONE_COLOR[visual.tone]}+ key={`${check.name}:${index}`}+ spin={visual.spin}+ title={check.name}+ value={check.name}+ trailing={+ <>+ {hasRequiredCheck && !check.required && (+ <span>{t('workingPanel.pr.check.optional')}</span>+ )}+ {duration && <span className={styles.duration}>{duration}</span>}+ {check.detailsUrl && <Icon icon={ExternalLinkIcon} size={12} />}+ </>+ }+ onClick={+ check.detailsUrl+ ? () => void electronSystemService.openExternalLink(check.detailsUrl!)+ : undefined+ }+ />+ );+ })}+ </div>+ );+});++ChecksList.displayName = 'PullRequestChecksList';++export default ChecksList;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/DockActionButton.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/DockActionButton.tsxnew file mode 100644index 00000000000..c4af929e037--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/DockActionButton.tsx@@ -0,0 +1,204 @@+import type {+ DeviceGitPullRequestAction,+ DeviceGitPullRequestDetail,+ DeviceGitPullRequestMergeMethod,+} from '@lobechat/types';+import { Button, type DropdownItem, SplitButton } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { type DockAction, PR_KEYS } from './mergeDockData';+import { MERGE_METHODS } from './mergeMethodStorage';+import type { TranslateKey } from './prVisual';+import type { PullRequestBusy } from './usePullRequestActions';++const tone = (base: string, hover: string) => `+ && > :where(button, a) {+ border-color: ${base};+ background: ${base};+ }++ &&:has(> :where(button, a):hover:not(:disabled, [aria-disabled='true'])) > :where(button, a) {+ border-color: ${hover};+ background: ${hover};+ }+`;++const styles = createStaticStyles(({ css, cssVar }) => ({+ toneError: css`+ ${tone(cssVar.colorError, cssVar.colorErrorHover)}+ `,+ toneSuccess: css`+ ${tone(cssVar.colorSuccess, cssVar.colorSuccessHover)}+ `,+}));++const TONE_CLASS = {+ error: styles.toneError,+ plain: undefined,+ success: styles.toneSuccess,+};++type SplitAction = Extract<DockAction, { kind: 'merge' | 'autoMerge' | 'updateBranch' }>;++const UPDATE_BRANCH_ACTION: SplitAction = { kind: 'updateBranch', tone: 'success' };++interface DockActionButtonProps {+ action: DockAction;+ busy?: PullRequestBusy;+ bypass?: boolean;+ detail: DeviceGitPullRequestDetail;+ onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;+ onPickMethod: (method: DeviceGitPullRequestMergeMethod) => void;+ onToggleBypass: (bypass: boolean) => void;+ secondary?: boolean;+}++const DockActionButton = memo<DockActionButtonProps>(+ ({ action, busy, bypass, detail, onAction, onPickMethod, onToggleBypass, secondary }) => {+ const { t } = useTranslation('chat');+ const tr = t as unknown as TranslateKey;++ const methodItems: DropdownItem[] = [+ ...MERGE_METHODS.map((item) => ({+ desc: tr(`workingPanel.pr.method.${item}.desc`, { base: detail.baseRefName }),+ key: item,+ label: tr(PR_KEYS.method[item]),+ onClick: () => onPickMethod(item),+ })),+ ...(bypass === undefined+ ? []+ : [+ { type: 'divider' as const },+ {+ checked: bypass,+ danger: true,+ desc: t('workingPanel.pr.hint.bypass'),+ key: 'bypass',+ label: t('workingPanel.pr.bypass'),+ onCheckedChange: onToggleBypass,+ type: 'checkbox' as const,+ },+ ]),+ ];++ const splitButton = (+ split: SplitAction,+ label: string,+ items: DropdownItem[],+ onClick: () => void,+ ) => (+ <SplitButton+ className={secondary ? undefined : TONE_CLASS[split.tone]}+ loading={split.busy}+ size={'small'}+ type={secondary || split.tone === 'plain' ? 'default' : 'primary'}+ >+ <SplitButton.Main onClick={onClick}>+ {split.busy && split.busyLabelKey ? tr(split.busyLabelKey) : label}+ </SplitButton.Main>+ <SplitButton.Menu items={items} placement={'topRight'} />+ </SplitButton>+ );++ switch (action.kind) {+ case 'merge': {+ const label = action.admin+ ? `${tr(PR_KEYS.method[action.method])} · ${t('workingPanel.pr.action.bypassSuffix')}`+ : tr(PR_KEYS.method[action.method]);+ return splitButton(+ action,+ label,+ methodItems,+ () =>+ void onAction({+ admin: action.admin,+ headRefOid: detail.headRefOid,+ method: action.method,+ type: 'merge',+ }),+ );+ }+ case 'autoMerge': {+ return splitButton(+ action,+ t('workingPanel.pr.action.autoMerge'),+ methodItems,+ () =>+ void onAction({+ headRefOid: detail.headRefOid,+ method: action.method,+ type: 'autoMerge',+ }),+ );+ }+ case 'updateBranch': {+ return splitButton(+ secondary ? { ...UPDATE_BRANCH_ACTION, busy: busy === 'updateBranch' } : action,+ t('workingPanel.pr.action.updateBranch'),+ [+ {+ key: 'merge',+ label: t('workingPanel.pr.action.updateBranch.merge'),+ onClick: () => void onAction({ method: 'merge', type: 'updateBranch' }),+ },+ {+ key: 'rebase',+ label: t('workingPanel.pr.action.updateBranch.rebase'),+ onClick: () => void onAction({ method: 'rebase', type: 'updateBranch' }),+ },+ ],+ () => void onAction({ method: 'merge', type: 'updateBranch' }),+ );+ }+ case 'ready': {+ return (+ <Button+ loading={action.busy}+ size={'small'}+ type={'primary'}+ onClick={() => void onAction({ type: 'ready' })}+ >+ {action.busy && action.busyLabelKey+ ? tr(action.busyLabelKey)+ : t('workingPanel.pr.action.ready')}+ </Button>+ );+ }+ case 'deleteBranch': {+ return (+ <Button+ loading={busy === 'deleteBranch'}+ size={'small'}+ onClick={() => void onAction({ head: detail.headRefName, type: 'deleteBranch' })}+ >+ {t('workingPanel.pr.action.deleteBranch')}+ </Button>+ );+ }+ case 'reopen': {+ return (+ <Button+ loading={busy === 'reopen'}+ size={'small'}+ onClick={() => void onAction({ type: 'reopen' })}+ >+ {t('workingPanel.pr.action.reopen')}+ </Button>+ );+ }+ case 'disabled': {+ return (+ <Button disabled size={'small'} type={'primary'}>+ {tr(action.labelKey)}+ </Button>+ );+ }+ }+ },+);++DockActionButton.displayName = 'PullRequestDockActionButton';++export default DockActionButton;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsxnew file mode 100644index 00000000000..90bf808c6f9--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/Header.tsx@@ -0,0 +1,217 @@+import type { DeviceGitPullRequestAction, DeviceGitPullRequestDetail } from '@lobechat/types';+import { copyToClipboard, Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cx } from 'antd-style';+import {+ ArrowRightIcon,+ ChevronDownIcon,+ EllipsisIcon,+ ExternalLinkIcon,+ LinkIcon,+} from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { electronSystemService } from '@/services/electron/system';+import { useGitRemoteBranches } from '@/store/device';++import { rowStyles } from '../Overview/OverviewRow';+import { sectionStyles } from '../Overview/sectionStyles';+import { getDetailVisual } from './prVisual';++const styles = createStaticStyles(({ css, cssVar }) => ({+ actions: css`+ flex-shrink: 0;+ margin-block-start: -2px;+ `,+ head: css`+ padding-block: 10px 8px;+ padding-inline: 8px;+ `,+ meta: css`+ flex-wrap: wrap;++ margin-block-start: 6px;++ font-size: 12px;+ line-height: 18px;+ color: ${cssVar.colorTextTertiary};+ `,+ ref: css`+ overflow: hidden;++ max-width: 160px;+ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillSecondary};+ `,+ refButton: css`+ cursor: pointer;+ display: inline-flex;+ gap: 3px;+ align-items: center;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ stats: css`+ font-variant-numeric: tabular-nums;+ `,+ title: css`+ flex: 1;++ min-width: 0;++ font-size: 15px;+ font-weight: 600;+ line-height: 22px;+ color: ${cssVar.colorText};+ overflow-wrap: anywhere;+ `,+}));++interface HeaderProps {+ activityLoaded?: boolean;+ detail: DeviceGitPullRequestDetail;+ deviceId?: string;+ onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;+ workingDirectory: string;+}++const Header = memo<HeaderProps>(+ ({ activityLoaded = true, detail, deviceId, onAction, workingDirectory }) => {+ const { t } = useTranslation('chat');+ const visual = getDetailVisual(detail);+ const canChangeBase = detail.viewerCanWrite && detail.state === 'open';+ const [basePickerOpen, setBasePickerOpen] = useState(false);+ const { data: remoteBranches } = useGitRemoteBranches(+ workingDirectory,+ canChangeBase && basePickerOpen,+ deviceId,+ );+ const baseItems: DropdownItem[] = remoteBranches+ ? remoteBranches+ .map((branch) => branch.name.replace(/^[^/]+\//, ''))+ .filter((name) => name !== detail.headRefName)+ .map((name) => ({+ key: name,+ label: name,+ onClick: () => {+ if (name !== detail.baseRefName) void onAction({ base: name, type: 'changeBase' });+ },+ }))+ : [{ disabled: true, key: 'loading', label: t('workingPanel.review.baseRef.loading') }];++ const openOnGithub = () => void electronSystemService.openExternalLink(detail.url);++ const menuItems: DropdownItem[] = [+ {+ icon: <Icon icon={LinkIcon} size={14} />,+ key: 'copy',+ label: t('workingPanel.pr.menu.copyLink'),+ onClick: async () => {+ await copyToClipboard(detail.url);+ toast.success(t('workingPanel.pr.menu.copied'));+ },+ },+ ...(detail.viewerCanWrite && detail.state !== 'merged'+ ? [+ { type: 'divider' as const },+ detail.state === 'open'+ ? {+ danger: true,+ key: 'close',+ label: t('workingPanel.pr.menu.close'),+ onClick: () => void onAction({ type: 'close' }),+ }+ : {+ key: 'reopen',+ label: t('workingPanel.pr.menu.reopen'),+ onClick: () => void onAction({ type: 'reopen' }),+ },+ ]+ : []),+ ];++ return (+ <div className={styles.head}>+ <Flexbox horizontal align={'flex-start'} gap={6}>+ <span className={styles.title}>+ <span className={rowStyles.num}>#{detail.number}</span>+ {detail.title}+ </span>+ <Flexbox horizontal className={styles.actions} gap={2}>+ <ActionIcon+ icon={ExternalLinkIcon}+ size={'small'}+ title={t('workingPanel.pr.menu.openOnGithub')}+ onClick={openOnGithub}+ />+ <DropdownMenu items={menuItems} placement={'bottomRight'}>+ <ActionIcon icon={EllipsisIcon} size={'small'} />+ </DropdownMenu>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'center'} className={styles.meta} gap={6}>+ <span+ className={sectionStyles.pill}+ style={{+ background: `color-mix(in srgb, ${visual.color} 12%, transparent)`,+ color: visual.color,+ }}+ >+ <Icon icon={visual.icon} size={12} />+ {t(`workingPanel.pr.state.${visual.state}`)}+ </span>+ <span className={styles.ref} title={detail.headRefName}>+ {detail.headRefName}+ </span>+ <Icon icon={ArrowRightIcon} size={11} />+ {canChangeBase ? (+ <DropdownMenu+ virtual+ items={baseItems}+ placement={'bottomLeft'}+ onOpenChange={setBasePickerOpen}+ >+ <span+ className={cx(styles.ref, styles.refButton)}+ role={'button'}+ tabIndex={0}+ title={t('workingPanel.pr.header.changeBase')}+ >+ {detail.baseRefName}+ <Icon icon={ChevronDownIcon} size={10} />+ </span>+ </DropdownMenu>+ ) : (+ <span className={styles.ref} title={detail.baseRefName}>+ {detail.baseRefName}+ </span>+ )}+ {activityLoaded && (+ <span>· {t('workingPanel.pr.header.commits', { count: detail.commits.length })}</span>+ )}+ <span className={styles.stats}>+ <span className={rowStyles.changeAdditions}>+{detail.additions}</span>{' '}+ <span className={rowStyles.changeDeletions}>−{detail.deletions}</span>+ </span>+ </Flexbox>+ </div>+ );+ },+);++Header.displayName = 'PullRequestHeader';++export default Header;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsxnew file mode 100644index 00000000000..8cabcb1cd2f--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/MergeDock.tsx@@ -0,0 +1,265 @@+import type { DeviceGitPullRequestAction, DeviceGitPullRequestDetail } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, ScrollArea } from '@lobehub/ui/base-ui';+import { createStaticStyles, cx } from 'antd-style';+import { ArrowUpIcon, ChevronRightIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import ChecksList from './ChecksList';+import DockActionButton from './DockActionButton';+import { type DockAction, type MergeDockInput, resolveMergeDock } from './mergeDockData';+import { readMergeMethod, writeMergeMethod } from './mergeMethodStorage';+import { DOCK_ICON, TONE_COLOR, type TranslateKey } from './prVisual';+import type { PullRequestBusy } from './usePullRequestActions';++const BUSY_MAP: Partial<Record<PullRequestBusy, NonNullable<MergeDockInput['ui']['busy']>>> = {+ autoMerge: 'autoMerge',+ merge: 'merge',+ ready: 'ready',+ updateBranch: 'update',+};++const UPDATE_BRANCH: DockAction = { kind: 'updateBranch', tone: 'success' };++const styles = createStaticStyles(({ css, cssVar }) => ({+ actionBar: css`+ flex-wrap: wrap;+ padding-block-start: 10px;+ `,+ checks: css`+ margin-inline-start: 22px;++ > summary {+ cursor: pointer;++ display: flex;+ gap: 4px;+ align-items: center;++ font-size: 12px;+ line-height: 18px;+ color: ${cssVar.colorTextTertiary};+ list-style: none;++ &::-webkit-details-marker {+ display: none;+ }+ }++ &[open] > summary svg {+ transform: rotate(90deg);+ }+ `,+ checksList: css`+ max-height: min(240px, 35vh);+ `,+ dock: css`+ flex-shrink: 0;++ padding-block: 10px 12px;+ padding-inline: 16px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ local: css`+ flex-shrink: 0;++ padding-block: 10px;+ padding-inline: 16px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ headline: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ font-size: 13px;+ font-weight: 600;+ line-height: 20px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ headlineWrap: css`+ overflow-wrap: anywhere;+ white-space: normal;+ `,+ icon: css`+ flex-shrink: 0;+ `,+ sub: css`+ padding-inline-start: 22px;++ font-size: 12px;+ line-height: 18px;+ color: ${cssVar.colorTextTertiary};+ overflow-wrap: anywhere;+ `,+ trailing: css`+ flex-shrink: 0;+ margin-inline-end: -6px;+ `,+}));++interface MergeDockProps {+ busy?: PullRequestBusy;+ contextLoading?: boolean;+ detail: DeviceGitPullRequestDetail;+ error?: string;+ local?: MergeDockInput['local'];+ onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;+ onDismissError: () => void;+ onPush: () => Promise<boolean>;+ onRetry: () => void;+}++const MergeDock = memo<MergeDockProps>(+ ({ busy, contextLoading, detail, error, local, onAction, onDismissError, onPush, onRetry }) => {+ const { t } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const tr = t as unknown as TranslateKey;+ const [bypass, setBypass] = useState(false);+ const [method, setMethod] = useState(readMergeMethod);++ const model = resolveMergeDock({+ detail,+ local,+ ui: { busy: busy && BUSY_MAP[busy], bypass, contextLoading, error, method },+ });+ const { status } = model;+ const isError = status.key === 'error';+ const hasFailedChecks = detail.checks.some(+ (check) => check.status === 'failure' || check.status === 'cancelled',+ );+ const reasons = model.reasons+ .map((reason) => tr(reason.labelKey, reason.labelParams))+ .join(' · ');++ return (+ <>+ {model.showPush && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.local}+ gap={8}+ justify={'space-between'}+ >+ <span>{t('workingPanel.pr.reason.localAhead', { count: local?.ahead ?? 0 })}</span>+ <Button+ icon={<Icon icon={ArrowUpIcon} size={12} />}+ loading={busy === 'push'}+ size={'small'}+ onClick={() => void onPush()}+ >+ {busy === 'push'+ ? t('workingPanel.pr.action.pushing')+ : t('workingPanel.pr.action.push', { count: local?.ahead ?? 0 })}+ </Button>+ </Flexbox>+ )}+ <div className={styles.dock}>+ <Flexbox horizontal align={'flex-start'} gap={8}>+ <Icon+ className={styles.icon}+ color={TONE_COLOR[status.tone]}+ icon={DOCK_ICON[status.icon]}+ size={14}+ spin={status.icon === 'spinner'}+ style={{ marginBlockStart: 3 }}+ />+ <span+ className={cx(styles.headline, isError && styles.headlineWrap)}+ style={isError ? { color: TONE_COLOR.error } : undefined}+ >+ {tr(status.labelKey, status.labelParams)}+ </span>+ {isError && (+ <Flexbox horizontal className={styles.trailing} gap={2}>+ <Button size={'small'} type={'text'} onClick={onDismissError}>+ {t('workingPanel.pr.dismiss')}+ </Button>+ <Button size={'small'} type={'text'} onClick={onRetry}>+ {tCommon('retry')}+ </Button>+ </Flexbox>+ )}+ {status.key === 'autoMerge' && (+ <Button+ className={styles.trailing}+ loading={busy === 'disableAutoMerge'}+ size={'small'}+ type={'text'}+ onClick={() => void onAction({ type: 'disableAutoMerge' })}+ >+ {t('workingPanel.pr.action.disableAutoMerge')}+ </Button>+ )}+ </Flexbox>+ {model.reasons.length > 0 &&+ (hasFailedChecks ? (+ <details className={styles.checks}>+ <summary>+ <Icon icon={ChevronRightIcon} size={12} />+ {reasons}+ </summary>+ <ScrollArea+ disableContentFit+ scrollFade+ style={{ marginBlockStart: 6 }}+ viewportProps={{+ 'aria-label': t('workingPanel.pr.section.checks'),+ 'className': styles.checksList,+ 'role': 'region',+ 'tabIndex': 0,+ }}+ >+ <ChecksList checks={detail.checks} />+ </ScrollArea>+ </details>+ ) : (+ <div className={styles.sub}>{reasons}</div>+ ))}+ {model.hintKey && <div className={styles.sub}>{tr(model.hintKey, model.hintParams)}</div>}+ {model.action && (+ <Flexbox horizontal align={'center'} className={styles.actionBar} gap={8}>+ {model.showUpdateBranch && (+ <DockActionButton+ secondary+ action={UPDATE_BRANCH}+ busy={busy}+ detail={detail}+ onAction={onAction}+ onPickMethod={() => {}}+ onToggleBypass={() => {}}+ />+ )}+ <DockActionButton+ action={model.action}+ busy={busy}+ bypass={model.bypassAvailable ? bypass : undefined}+ detail={detail}+ onAction={onAction}+ onToggleBypass={setBypass}+ onPickMethod={(next) => {+ setMethod(next);+ writeMergeMethod(next);+ }}+ />+ </Flexbox>+ )}+ </div>+ </>+ );+ },+);++MergeDock.displayName = 'PullRequestMergeDock';++export default MergeDock;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsxnew file mode 100644index 00000000000..09ef9ef8812--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/Sections.tsx@@ -0,0 +1,220 @@+import type {+ DeviceGitPullRequestAction,+ DeviceGitPullRequestActivity,+ DeviceGitPullRequestDetail,+} from '@lobechat/types';+import { Flexbox, Icon, Markdown } from '@lobehub/ui';+import { Button, Skeleton } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ ChevronDownIcon,+ ChevronRightIcon,+ FolderOpenIcon,+ GitCommitHorizontalIcon,+} from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';+import type { SWRResponse } from 'swr';++import { ChevronRight, OverviewRow, rowStyles } from '../Overview/OverviewRow';+import { sectionStyles } from '../Overview/sectionStyles';+import ActivityTimeline from './ActivityTimeline';+import ChecksList from './ChecksList';+import { timeAgo } from './prVisual';+import type { PullRequestBusy } from './usePullRequestActions';++const styles = createStaticStyles(({ css, cssVar }) => ({+ body: css`+ overflow: hidden;++ min-width: 0;+ padding-block: 2px 6px;+ padding-inline: 8px;++ overflow-wrap: anywhere;++ table {+ overflow-x: auto;+ display: block;+ max-width: 100%;+ }++ img,+ video {+ max-width: 100%;+ }++ pre {+ overflow-x: auto;+ max-width: 100%;+ }+ `,+ header: css`+ cursor: pointer;+ user-select: none;+ gap: 6px;+ `,+ sha: css`+ font-family: ${cssVar.fontFamilyCode};+ `,+}));++interface SectionProps {+ children: ReactNode;+ count?: ReactNode;+ onToggle?: () => void;+ open?: boolean;+ title: string;+}++const Section = memo<SectionProps>(({ children, count, onToggle, open = true, title }) => (+ <Flexbox className={sectionStyles.section}>+ <Flexbox+ horizontal+ align={'center'}+ role={onToggle ? 'button' : undefined}+ className={cx(+ sectionStyles.sectionHeader,+ sectionStyles.sectionTitle,+ onToggle && styles.header,+ )}+ onClick={onToggle}+ >+ {onToggle && <Icon icon={open ? ChevronDownIcon : ChevronRightIcon} size={12} />}+ {title}+ {count !== undefined && <span className={sectionStyles.count}>{count}</span>}+ </Flexbox>+ {open && children}+ </Flexbox>+));++Section.displayName = 'PullRequestSection';++interface SectionsProps {+ activity: Pick<+ SWRResponse<DeviceGitPullRequestActivity>,+ 'data' | 'error' | 'isValidating' | 'mutate'+ >;+ busy?: PullRequestBusy;+ detail: DeviceGitPullRequestDetail;+ onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;+ onOpenTab: (tab: string) => void;+}++const Sections = memo<SectionsProps>(({ activity, busy, detail, onAction, onOpenTab }) => {+ const { t } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const activityPlaceholder = activity.error ? (+ <Flexbox gap={8}>+ <span>{t('workingPanel.pr.error.load')}</span>+ <Button loading={activity.isValidating} size={'small'} onClick={() => void activity.mutate()}>+ {tCommon('retry')}+ </Button>+ </Flexbox>+ ) : (+ <Skeleton.Text rows={3} />+ );+ const [open, setOpen] = useState({+ activity: true,+ checks: false,+ commits: false,+ description: true,+ });+ const toggle = (key: keyof typeof open) => () => setOpen((o) => ({ ...o, [key]: !o[key] }));++ const failing = detail.checks.filter(+ (check) => check.status === 'failure' || check.status === 'cancelled',+ ).length;+ const running = detail.checks.filter((check) => check.status === 'pending').length;+ const checksCount = failing ? (+ <span style={{ color: cssVar.colorError }}>+ {t('workingPanel.pr.checks.failing', { count: failing })}+ </span>+ ) : running ? (+ <span style={{ color: cssVar.colorWarning }}>+ {t('workingPanel.pr.checks.running', { count: running })}+ </span>+ ) : (+ detail.checks.length+ );++ return (+ <>+ {detail.body && (+ <Section+ open={open.description}+ title={t('workingPanel.pr.section.description')}+ onToggle={toggle('description')}+ >+ <Markdown allowHtml className={styles.body} fontSize={13} variant={'chat'}>+ {detail.body}+ </Markdown>+ </Section>+ )}+ <Section count={detail.changedFiles} title={t('workingPanel.pr.section.files')}>+ <OverviewRow+ icon={FolderOpenIcon}+ value={t('workingPanel.pr.files.openReview')}+ trailing={+ <>+ <span className={rowStyles.changeAdditions}>+{detail.additions}</span>+ <span className={rowStyles.changeDeletions}>−{detail.deletions}</span>+ <ChevronRight />+ </>+ }+ onClick={() => onOpenTab('review')}+ />+ </Section>+ {detail.checks.length > 0 && (+ <Section+ count={checksCount}+ open={open.checks}+ title={t('workingPanel.pr.section.checks')}+ onToggle={toggle('checks')}+ >+ <ChecksList checks={detail.checks} />+ </Section>+ )}+ <Section+ count={activity.data ? detail.commits.length : undefined}+ open={open.commits}+ title={t('workingPanel.pr.section.commits')}+ onToggle={toggle('commits')}+ >+ {!activity.data+ ? activityPlaceholder+ : detail.commits.map((commit) => (+ <OverviewRow+ weak+ icon={GitCommitHorizontalIcon}+ key={commit.sha}+ title={commit.message}+ value={commit.message.split('\n')[0]}+ trailing={+ <>+ <span className={styles.sha}>{commit.sha.slice(0, 7)}</span>+ {timeAgo(commit.committedAt)}+ </>+ }+ />+ ))}+ </Section>+ <Section+ count={activity.data ? detail.comments.length + detail.reviews.length : undefined}+ open={open.activity}+ title={t('workingPanel.pr.section.activity')}+ onToggle={toggle('activity')}+ >+ {activity.data ? (+ <ActivityTimeline busy={busy} detail={detail} onAction={onAction} />+ ) : (+ activityPlaceholder+ )}+ </Section>+ </>+ );+});++Sections.displayName = 'PullRequestSections';++export default Sections;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/Skeleton.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/Skeleton.tsxnew file mode 100644index 00000000000..4fae1874bab--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/Skeleton.tsx@@ -0,0 +1,114 @@+import type { DeviceGitLinkedPullRequest } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Skeleton } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { getPullRequestState } from '@/features/AgentSidebar/Topic/List/Item/metaCardData';++import { sectionStyles } from '../Overview/sectionStyles';++const styles = createStaticStyles(({ css, cssVar }) => ({+ dock: css`+ flex-shrink: 0;+ padding-block: 8px 10px;+ padding-inline: 8px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ head: css`+ padding-block: 10px 8px;+ padding-inline: 8px;+ `,+ root: css`+ flex: 1;+ min-height: 0;+ `,+ row: css`+ min-height: 32px;+ padding-block: 5px;+ padding-inline: 8px;+ `,+ sectionBody: css`+ padding-block: 2px 6px;+ padding-inline: 8px;+ `,+}));++const Row = ({ trailing = 48 }: { trailing?: number }) => (+ <Flexbox horizontal align={'center'} className={styles.row} gap={8}>+ <Skeleton height={14} radius={4} width={14} />+ <Skeleton.Text width={'55%'} />+ <Skeleton height={12} radius={4} style={{ marginInlineStart: 'auto' }} width={trailing} />+ </Flexbox>+);++const SectionTitle = ({ width = 64 }: { width?: number }) => (+ <div className={sectionStyles.sectionHeader}>+ <Skeleton height={10} radius={4} width={width} />+ </div>+);++const PullRequestSkeleton = memo(({ summary }: { summary?: DeviceGitLinkedPullRequest }) => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox className={styles.root}>+ <Flexbox className={styles.root}>+ <div className={styles.head}>+ {summary ? (+ <>+ <div>+ #{summary.number} {summary.title}+ </div>+ <div>+ {t(+ `workingPanel.pr.state.${summary.isDraft && getPullRequestState(summary) === 'open' ? 'draft' : getPullRequestState(summary)}`,+ )}+ </div>+ </>+ ) : (+ <Skeleton.Text fontSize={15} rows={2} width={['92%', '60%']} />+ )}+ <Flexbox horizontal align={'center'} gap={6} style={{ marginBlockStart: 6 }}>+ <Skeleton height={20} radius={6} width={56} />+ <Skeleton height={18} radius={4} width={96} />+ <Skeleton height={18} radius={4} width={64} />+ </Flexbox>+ </div>+ <Flexbox className={sectionStyles.section}>+ <SectionTitle width={72} />+ <div className={styles.sectionBody}>+ <Skeleton.Text fontSize={13} rows={3} width={['100%', '88%', '46%']} />+ </div>+ </Flexbox>+ <Flexbox className={sectionStyles.section}>+ <SectionTitle width={40} />+ <Row trailing={72} />+ </Flexbox>+ <Flexbox className={sectionStyles.section}>+ <SectionTitle width={56} />+ </Flexbox>+ <Flexbox className={sectionStyles.section}>+ <SectionTitle width={52} />+ <Row />+ <Row />+ </Flexbox>+ </Flexbox>+ <div className={styles.dock}>+ <Row trailing={40} />+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ style={{ paddingBlock: '6px 0', paddingInline: 8 }}+ >+ <Skeleton height={24} radius={6} width={'100%'} />+ </Flexbox>+ </div>+ </Flexbox>+ );+});++PullRequestSkeleton.displayName = 'PullRequestSkeleton';++export default PullRequestSkeleton;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.tsnew file mode 100644index 00000000000..4d1b6e354ae--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeDockData.test.ts@@ -0,0 +1,394 @@+import type { DeviceGitPullRequestDetail } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { type MergeDockInput, PR_KEYS, resolveMergeDock } from '../mergeDockData';++const makeDetail = (+ overrides: Partial<DeviceGitPullRequestDetail> = {},+): DeviceGitPullRequestDetail => ({+ additions: 10,+ author: 'innei',+ autoMerge: null,+ baseBehindBy: 0,+ baseRefName: 'main',+ body: '',+ changedFiles: 2,+ checks: [{ name: 'ci', required: true, status: 'success' }],+ comments: [],+ commits: [{ author: 'innei', committedAt: '2026-09-13T00:00:00Z', message: 'fix', sha: 'abc' }],+ deletions: 2,+ headRefName: 'feat/x',+ headRefOid: 'a'.repeat(40),+ isCrossRepository: false,+ isDraft: false,+ mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN',+ number: 1,+ repo: { name: 'lobe-chat', owner: 'lobehub' },+ reviewDecision: 'APPROVED',+ reviews: [{ author: 'foo', state: 'APPROVED', submittedAt: '2026-09-13T00:00:00Z' }],+ state: 'open',+ title: 'PR',+ url: 'https://github.com/lobehub/lobe-chat/pull/1',+ viewerCanBypass: false,+ viewerCanWrite: true,+ ...overrides,+});++const makeInput = (overrides: Partial<MergeDockInput> = {}): MergeDockInput => ({+ detail: makeDetail(),+ ui: { bypass: false, method: 'squash' },+ ...overrides,+});++const reasonKeys = (result: ReturnType<typeof resolveMergeDock>) =>+ result.reasons.map((reason) => reason.labelKey);++describe('resolveMergeDock', () => {+ it('clean: ready status, green merge action, merge hint', () => {+ const result = resolveMergeDock(makeInput());+ expect(result.status).toMatchObject({ key: 'ready', tone: 'success' });+ expect(result.reasons).toEqual([]);+ expect(result.action).toEqual({+ admin: false,+ kind: 'merge',+ method: 'squash',+ tone: 'success',+ });+ expect(result.bypassAvailable).toBe(false);+ expect(result.hintKey).toBe(PR_KEYS.hint.merge);+ });++ it('pending: required check pending under BLOCKED waits and offers auto-merge', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ checks: [{ name: 'ci', required: true, status: 'pending' }],+ mergeStateStatus: 'BLOCKED',+ }),+ }),+ );+ expect(result.checksStatus).toBe('pending');+ expect(result.status).toMatchObject({ key: 'waiting', tone: 'warning' });+ expect(reasonKeys(result)).toEqual([PR_KEYS.reason.checksPending]);+ expect(result.action).toEqual({ kind: 'autoMerge', method: 'squash', tone: 'plain' });+ expect(result.hintKey).toBeUndefined();+ });++ it('pendingUnprotected: mergeable while checks run turns the merge action amber', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({ checks: [{ name: 'ci', required: false, status: 'pending' }] }),+ }),+ );+ expect(result.status.key).toBe('waiting');+ expect(result.action).toEqual({+ admin: false,+ kind: 'merge',+ method: 'squash',+ tone: 'plain',+ });+ });++ it('optional failure: ready headline with a secondary warning when merging is allowed', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ mergeStateStatus: 'UNSTABLE',+ checks: [+ { name: 'ci', required: true, status: 'success' },+ { name: 'verify', required: false, status: 'failure' },+ ],+ }),+ }),+ );+ expect(result.status).toMatchObject({ key: 'ready', labelKey: PR_KEYS.status.ready });+ expect(result.reasons).toEqual([+ { labelKey: PR_KEYS.reason.optionalFailing, labelParams: { count: 1 } },+ ]);+ expect(result.action).toMatchObject({ kind: 'merge', tone: 'plain' });+ });++ it('optional failures do not hide a branch protection blocker', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ mergeStateStatus: 'BLOCKED',+ checks: [{ name: 'optional', required: false, status: 'failure' }],+ }),+ }),+ );+ expect(result.status.key).toBe('blocked');+ expect(result.action?.kind).toBe('disabled');+ });++ it('autoMerge: armed status with method and a disabled waiting action', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ autoMerge: { method: 'squash' },+ checks: [{ name: 'ci', required: true, status: 'pending' }],+ mergeStateStatus: 'BLOCKED',+ }),+ }),+ );+ expect(result.status).toMatchObject({+ key: 'autoMerge',+ labelParams: { method: 'squash' },+ tone: 'merged',+ });+ expect(result.action).toEqual({ kind: 'disabled', labelKey: PR_KEYS.action.waiting });+ });++ it('ciFailed: blocked status lists the failing count and disables the action', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ checks: [+ { name: 'ci', required: true, status: 'failure' },+ { name: 'lint', required: true, status: 'cancelled' },+ ],+ mergeStateStatus: 'BLOCKED',+ }),+ }),+ );+ expect(result.checksStatus).toBe('failure');+ expect(result.status).toMatchObject({ key: 'blocked', tone: 'error' });+ expect(result.reasons).toEqual([+ { labelKey: PR_KEYS.reason.checksFailing, labelParams: { count: 2 } },+ ]);+ expect(result.action).toEqual({ kind: 'disabled', labelKey: PR_KEYS.method.squash });+ expect(result.bypassAvailable).toBe(false);+ expect(result.hintKey).toBeUndefined();+ });++ it('ciFailed+bypass: bypass status keeps the blockers listed and merges with --admin', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ checks: [{ name: 'ci', required: true, status: 'failure' }],+ mergeStateStatus: 'BLOCKED',+ viewerCanBypass: true,+ }),+ ui: { bypass: true, method: 'squash' },+ }),+ );+ expect(result.status).toMatchObject({ key: 'bypass', tone: 'error' });+ expect(reasonKeys(result)).toEqual([PR_KEYS.reason.checksFailing]);+ expect(result.action).toEqual({ admin: true, kind: 'merge', method: 'squash', tone: 'error' });+ expect(result.bypassAvailable).toBe(true);+ });++ it('blockedByRules: BLOCKED with nothing else failing names the branch rules', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ mergeStateStatus: 'BLOCKED' }) }),+ );+ expect(result.status.key).toBe('blocked');+ expect(reasonKeys(result)).toEqual([PR_KEYS.reason.rules]);+ });++ it('reviewRequired: blocked with a review reason', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ reviewDecision: 'REVIEW_REQUIRED' }) }),+ );+ expect(result.status.key).toBe('blocked');+ expect(reasonKeys(result)).toEqual([PR_KEYS.reason.reviewRequired]);+ });++ it('changesRequested: reason lists the requesting authors', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ reviewDecision: 'CHANGES_REQUESTED',+ reviews: [+ { author: 'foo', state: 'CHANGES_REQUESTED', submittedAt: '2026-09-13T00:00:00Z' },+ { author: 'bar', state: 'CHANGES_REQUESTED', submittedAt: '2026-09-13T00:00:00Z' },+ ],+ }),+ }),+ );+ expect(result.status.key).toBe('blocked');+ expect(result.reasons).toEqual([+ { labelKey: PR_KEYS.reason.changesRequested, labelParams: { authors: 'foo, bar' } },+ ]);+ });++ it('multipleBlockers: reasons are ordered checks → review → base', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ checks: [{ name: 'ci', required: true, status: 'failure' }],+ mergeStateStatus: 'BLOCKED',+ reviewDecision: 'REVIEW_REQUIRED',+ }),+ local: { ahead: 1 },+ }),+ );+ expect(reasonKeys(result)).toEqual([+ PR_KEYS.reason.checksFailing,+ PR_KEYS.reason.reviewRequired,+ ]);+ });++ it('conflicts: conflict status names the base and disables the action', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ mergeable: 'CONFLICTING' }) }),+ );+ expect(result.status).toMatchObject({+ icon: 'conflict',+ key: 'conflicts',+ labelParams: { base: 'main' },+ tone: 'error',+ });+ expect(result.reasons).toEqual([]);+ expect(result.action).toEqual({ kind: 'disabled', labelKey: PR_KEYS.action.conflicting });+ });++ it('behind: blocked with a behind reason and an updateBranch action', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ mergeStateStatus: 'BEHIND' }) }),+ );+ expect(result.status.key).toBe('blocked');+ expect(result.reasons).toEqual([+ { labelKey: PR_KEYS.reason.behind, labelParams: { base: 'main' } },+ ]);+ expect(result.action).toEqual({ kind: 'updateBranch', tone: 'success' });+ });++ it('behindUnprotected: base moved ahead without BEHIND offers Update branch beside merge', () => {+ const result = resolveMergeDock(makeInput({ detail: makeDetail({ baseBehindBy: 3 }) }));+ expect(result.action).toMatchObject({ kind: 'merge' });+ expect(result.showUpdateBranch).toBe(true);+ });++ it('behindProtected: BEHIND promotes Update branch to the primary action only', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ baseBehindBy: 3, mergeStateStatus: 'BEHIND' }) }),+ );+ expect(result.action).toEqual({ kind: 'updateBranch', tone: 'success' });+ expect(result.showUpdateBranch).toBe(false);+ });++ it('draft: neutral draft status, no reasons, ready action', () => {+ const result = resolveMergeDock(makeInput({ detail: makeDetail({ isDraft: true }) }));+ expect(result.status).toMatchObject({ key: 'draft', tone: 'neutral' });+ expect(result.reasons).toEqual([]);+ expect(result.action).toEqual({ kind: 'ready' });+ expect(result.bypassAvailable).toBe(false);+ });++ it('merged: merged-tone status and deleteBranch action', () => {+ const result = resolveMergeDock(makeInput({ detail: makeDetail({ state: 'merged' }) }));+ expect(result.status).toMatchObject({ key: 'merged', tone: 'merged' });+ expect(result.action).toEqual({ kind: 'deleteBranch' });+ expect(result.hintKey).toBe(PR_KEYS.hint.merged);+ expect(result.hintParams).toEqual({ head: 'feat/x' });+ });++ it('merged+fork: no deleteBranch action offered for a cross-repository PR', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ isCrossRepository: true, state: 'merged' }) }),+ );+ expect(result.action).toBeUndefined();+ expect(result.hintKey).toBe(PR_KEYS.hint.merged);+ });++ it('merged+readOnly: still shows the merged hint, not the readOnly hint', () => {+ const result = resolveMergeDock(+ makeInput({ detail: makeDetail({ state: 'merged', viewerCanWrite: false }) }),+ );+ expect(result.action).toBeUndefined();+ expect(result.hintKey).toBe(PR_KEYS.hint.merged);+ });++ it('closed: error-tone status and reopen action', () => {+ const result = resolveMergeDock(makeInput({ detail: makeDetail({ state: 'closed' }) }));+ expect(result.status).toMatchObject({ key: 'closed', tone: 'error' });+ expect(result.action).toEqual({ kind: 'reopen' });+ });++ it('local changes do not alter remote merge status or reasons', () => {+ const remote = makeDetail({+ checks: [{ name: 'optional', required: false, status: 'failure' }],+ });+ const local = { ahead: 2, dirtyFiles: 22 };+ const withoutLocal = resolveMergeDock(makeInput({ detail: remote }));+ const result = resolveMergeDock(makeInput({ detail: remote, local }));+ expect(result.status).toEqual(withoutLocal.status);+ expect(result.reasons).toEqual(withoutLocal.reasons);+ expect(result.hintKey).toBe(withoutLocal.hintKey);+ expect(result.showPush).toBe(true);+ expect(result.action).toEqual(withoutLocal.action);+ });++ it('readOnly: no action, no bypass, and the readOnly hint survives reasons', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({ reviewDecision: 'REVIEW_REQUIRED', viewerCanWrite: false }),+ }),+ );+ expect(result.action).toBeUndefined();+ expect(result.bypassAvailable).toBe(false);+ expect(reasonKeys(result)).toEqual([PR_KEYS.reason.reviewRequired]);+ expect(result.hintKey).toBe(PR_KEYS.hint.readOnly);+ expect(result.hintParams).toEqual({ repo: 'lobehub/lobe-chat' });+ });++ it('unknown: UNKNOWN mergeability shows a spinner status and disables the action', () => {+ const result = resolveMergeDock(makeInput({ detail: makeDetail({ mergeable: 'UNKNOWN' }) }));+ expect(result.status).toMatchObject({ icon: 'spinner', key: 'calculating' });+ expect(result.reasons).toEqual([]);+ expect(result.action).toEqual({ kind: 'disabled', labelKey: PR_KEYS.action.calculating });+ expect(result.hintKey).toBe(PR_KEYS.hint.calculating);+ });++ it('actionError: error status carries the message and clears the hint', () => {+ const result = resolveMergeDock(+ makeInput({ ui: { bypass: false, error: 'gh: failed', method: 'squash' } }),+ );+ expect(result.status).toMatchObject({+ key: 'error',+ labelParams: { message: 'gh: failed' },+ tone: 'error',+ });+ expect(result.hintKey).toBeUndefined();+ expect(result.action).toEqual({+ admin: false,+ kind: 'merge',+ method: 'squash',+ tone: 'success',+ });+ });++ it('contextLoading: disables the action without flashing the readOnly hint', () => {+ const result = resolveMergeDock(+ makeInput({+ detail: makeDetail({+ viewerCanBypass: false,+ viewerCanWrite: false,+ checks: [{ name: 'not classified yet', required: false, status: 'failure' }],+ }),+ ui: { bypass: false, contextLoading: true, method: 'squash' },+ }),+ );+ expect(result.status.key).toBe('calculating');+ expect(result.reasons).toEqual([]);+ expect(result.action).toEqual({ kind: 'disabled', labelKey: PR_KEYS.action.calculating });+ expect(result.hintKey).toBeUndefined();+ expect(result.bypassAvailable).toBe(false);+ });++ it('busy: keeps the action kind/tone and attaches a busyLabelKey', () => {+ const result = resolveMergeDock(+ makeInput({ ui: { busy: 'merge', bypass: false, method: 'squash' } }),+ );+ expect(result.action).toEqual({+ admin: false,+ busy: true,+ busyLabelKey: PR_KEYS.action.merging,+ kind: 'merge',+ method: 'squash',+ tone: 'success',+ });+ });+});diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeMethodStorage.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeMethodStorage.test.tsnew file mode 100644index 00000000000..7b922470f94--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/mergeMethodStorage.test.ts@@ -0,0 +1,33 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { MERGE_METHOD_STORAGE_KEY, readMergeMethod, writeMergeMethod } from '../mergeMethodStorage';++describe('mergeMethodStorage', () => {+ afterEach(() => {+ window.localStorage.clear();+ vi.restoreAllMocks();+ });++ it('defaults to squash when nothing or garbage is stored', () => {+ expect(readMergeMethod()).toBe('squash');+ window.localStorage.setItem(MERGE_METHOD_STORAGE_KEY, 'yolo');+ expect(readMergeMethod()).toBe('squash');+ });++ it('persists the chosen method', () => {+ writeMergeMethod('rebase');+ expect(window.localStorage.getItem(MERGE_METHOD_STORAGE_KEY)).toBe('rebase');+ expect(readMergeMethod()).toBe('rebase');+ });++ it('survives a throwing localStorage', () => {+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new Error('blocked');+ });+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('blocked');+ });+ expect(() => writeMergeMethod('merge')).not.toThrow();+ expect(readMergeMethod()).toBe('squash');+ });+});diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.tsnew file mode 100644index 00000000000..283cd827788--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts@@ -0,0 +1,147 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceKeys } from '@/libs/swr/keys';++import { usePullRequestActions } from '../usePullRequestActions';++const runPullRequestAction = vi.hoisted(() => vi.fn());+const pushGitBranch = vi.hoisted(() => vi.fn());+const mutate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const toastError = vi.hoisted(() => vi.fn());++vi.mock('@/services/git', () => ({ gitService: { pushGitBranch, runPullRequestAction } }));+vi.mock('@/libs/swr', () => ({ mutate }));+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: toastError } }));++const params = { deviceId: 'dev-1', number: 7, workingDirectory: '/repo' };++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+};++describe('usePullRequestActions', () => {+ beforeEach(() => {+ runPullRequestAction.mockReset();+ pushGitBranch.mockReset();+ mutate.mockClear();+ toastError.mockReset();+ });++ it('marks busy during the action and clears it afterwards', async () => {+ const pending = deferred<{ success: boolean }>();+ runPullRequestAction.mockReturnValue(pending.promise);+ const { result } = renderHook(() =>+ usePullRequestActions({ ...params, mutateDetail: vi.fn().mockResolvedValue(undefined) }),+ );++ let run!: Promise<boolean>;+ act(() => {+ run = result.current.run({+ admin: true,+ headRefOid: 'a'.repeat(40),+ method: 'squash',+ type: 'merge',+ });+ });+ expect(result.current.busy).toBe('merge');+ expect(runPullRequestAction).toHaveBeenCalledWith({+ action: { admin: true, headRefOid: 'a'.repeat(40), method: 'squash', type: 'merge' },+ deviceId: 'dev-1',+ number: 7,+ path: '/repo',+ });++ await act(async () => {+ pending.resolve({ success: true });+ await run;+ });+ expect(result.current.busy).toBeUndefined();+ });++ it('revalidates detail, linked PR, ahead/behind and working tree on success', async () => {+ runPullRequestAction.mockResolvedValue({ success: true });+ const mutateDetail = vi.fn().mockResolvedValue(undefined);+ const { result } = renderHook(() => usePullRequestActions({ ...params, mutateDetail }));++ await act(async () => {+ expect(await result.current.run({ type: 'ready' })).toBe(true);+ });++ expect(mutateDetail).toHaveBeenCalledTimes(1);+ expect(mutate).toHaveBeenCalledWith(deviceKeys.gitPullRequestActivity('dev-1', '/repo', 7));+ expect(mutate).toHaveBeenCalledWith(deviceKeys.gitAheadBehind('dev-1', '/repo'));+ expect(mutate).toHaveBeenCalledWith(deviceKeys.gitWorkingTreeStatus('dev-1', '/repo'));+ const matcher = mutate.mock.calls.find(([key]) => typeof key === 'function')?.[0];+ expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/repo', 'feat/x', 7))).toBe(true);+ expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/other', 'feat/x'))).toBe(false);+ });++ it('keeps dock-action failures as error and retries the same action', async () => {+ runPullRequestAction.mockResolvedValueOnce({ error: 'base moved', success: false });+ const { result } = renderHook(() =>+ usePullRequestActions({ ...params, mutateDetail: vi.fn().mockResolvedValue(undefined) }),+ );++ await act(async () => {+ expect(+ await result.current.run({ headRefOid: 'a'.repeat(40), method: 'rebase', type: 'merge' }),+ ).toBe(false);+ });+ expect(result.current.error).toBe('base moved');+ expect(mutate).not.toHaveBeenCalled();+ expect(toastError).not.toHaveBeenCalled();++ runPullRequestAction.mockResolvedValueOnce({ success: true });+ await act(async () => {+ result.current.retry();+ });+ expect(runPullRequestAction).toHaveBeenLastCalledWith(+ expect.objectContaining({+ action: { headRefOid: 'a'.repeat(40), method: 'rebase', type: 'merge' },+ }),+ );+ expect(result.current.error).toBeUndefined();+ });++ it('toasts non-dock failures without touching the dock error', async () => {+ runPullRequestAction.mockRejectedValueOnce(new Error('gh exploded'));+ const { result } = renderHook(() =>+ usePullRequestActions({ ...params, mutateDetail: vi.fn().mockResolvedValue(undefined) }),+ );++ await act(async () => {+ expect(await result.current.run({ body: 'hi', type: 'comment' })).toBe(false);+ });+ expect(toastError).toHaveBeenCalledWith('gh exploded');+ expect(result.current.error).toBeUndefined();+ });++ it('ignores re-entry while an action is in flight', async () => {+ const pending = deferred<{ success: boolean }>();+ runPullRequestAction.mockReturnValue(pending.promise);+ pushGitBranch.mockResolvedValue({ success: true });+ const { result } = renderHook(() =>+ usePullRequestActions({ ...params, mutateDetail: vi.fn().mockResolvedValue(undefined) }),+ );++ let first!: Promise<boolean>;+ let second!: Promise<boolean>;+ act(() => {+ first = result.current.run({ type: 'ready' });+ second = result.current.push();+ });+ expect(await second).toBe(false);+ expect(pushGitBranch).not.toHaveBeenCalled();++ await act(async () => {+ pending.resolve({ success: true });+ await first;+ });+ expect(result.current.busy).toBeUndefined();+ });+});diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsxnew file mode 100644index 00000000000..134f413bb98--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx@@ -0,0 +1,190 @@+import type { DeviceGitLinkedPullRequest } from '@lobechat/types';+import { Empty, Flexbox, Icon } from '@lobehub/ui';+import { Button, ScrollArea } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { GlobeIcon, RefreshCwIcon, TriangleAlertIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { electronSystemService } from '@/services/electron/system';+import {+ useFetchGitAheadBehind,+ useFetchGitPullRequestActivity,+ useFetchGitPullRequestDetail,+ useFetchGitPullRequestMergeContext,+} from '@/store/device';++import { OverviewRow } from '../Overview/OverviewRow';+import { sectionStyles } from '../Overview/sectionStyles';+import Header from './Header';+import MergeDock from './MergeDock';+import Sections from './Sections';+import PullRequestSkeleton from './Skeleton';+import { usePullRequestActions } from './usePullRequestActions';++const styles = createStaticStyles(({ css }) => ({+ root: css`+ flex: 1;+ min-height: 0;+ `,+ scroll: css`+ overflow: hidden;+ flex: 1;+ min-height: 0;+ `,+ scrollContent: css`+ padding-block: 0 10px;+ `,+ viewport: css`+ overflow-x: hidden;+ `,+}));++interface PullRequestProps {+ active: boolean;+ deviceId?: string;+ number: number;+ onOpenTab: (tab: string) => void;+ summary?: DeviceGitLinkedPullRequest;+ url?: string;+ workingDirectory: string;+}++const PullRequest = memo<PullRequestProps>(+ ({ active, deviceId, number, onOpenTab, summary, url, workingDirectory }) => {+ const { t } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const {+ data,+ error: fetchError,+ isLoading,+ mutate,+ } = useFetchGitPullRequestDetail(deviceId, workingDirectory, number, { active });+ const activity = useFetchGitPullRequestActivity(+ deviceId,+ workingDirectory,+ data?.detail?.number,+ active && data?.detail?.state === 'open',+ );+ const { data: context } = useFetchGitPullRequestMergeContext(+ deviceId,+ workingDirectory,+ data?.detail ?? undefined,+ );+ const { data: aheadBehind } = useFetchGitAheadBehind(deviceId, workingDirectory);+ const actions = usePullRequestActions({+ deviceId,+ mutateDetail: mutate,+ number,+ workingDirectory,+ });++ const detail = useMemo(() => {+ const core = data?.detail ? { ...data.detail, ...activity.data } : undefined;+ if (!core || !context) return core ?? undefined;+ const required = new Set(context.requiredChecks);+ return {+ ...core,+ baseBehindBy: context.baseBehindBy,+ checks: core.checks.map((check) => ({ ...check, required: required.has(check.name) })),+ viewerCanBypass: context.viewerCanBypass,+ viewerCanWrite: context.viewerCanWrite,+ };+ }, [data?.detail, context, activity.data]);+ const externalUrl = detail?.url ?? url;++ if (isLoading && !data) return <PullRequestSkeleton summary={summary} />;++ if (data?.status === 'gh-missing')+ return (+ <Empty+ description={t('workingPanel.pr.ghMissing.desc')}+ icon={TriangleAlertIcon}+ iconColor={cssVar.colorWarning}+ title={t('workingPanel.pr.ghMissing.title')}+ action={+ <Flexbox horizontal gap={6}>+ <Button size={'small'} type={'primary'} onClick={() => void mutate()}>+ {t('workingPanel.pr.ghMissing.retry')}+ </Button>+ {externalUrl && (+ <Button+ icon={<Icon icon={GlobeIcon} size={12} />}+ size={'small'}+ onClick={() => void electronSystemService.openExternalLink(externalUrl)}+ >+ {t('workingPanel.pr.ghMissing.open')}+ </Button>+ )}+ </Flexbox>+ }+ />+ );++ if (!detail)+ return (+ <Flexbox className={sectionStyles.section}>+ <OverviewRow+ danger+ icon={TriangleAlertIcon}+ iconColor={cssVar.colorError}+ title={fetchError instanceof Error ? fetchError.message : undefined}+ value={t('workingPanel.pr.error.load')}+ trailing={+ <Button+ icon={<Icon icon={RefreshCwIcon} size={12} />}+ size={'small'}+ onClick={() => void mutate()}+ >+ {tCommon('retry')}+ </Button>+ }+ />+ </Flexbox>+ );++ const local = aheadBehind?.hasUpstream ? { ahead: aheadBehind.ahead } : undefined;++ return (+ <Flexbox className={styles.root}>+ <ScrollArea+ disableContentFit+ scrollFade+ className={styles.scroll}+ contentProps={{ className: styles.scrollContent }}+ viewportProps={{ className: styles.viewport, style: { overflowX: 'hidden' } }}+ >+ <Header+ activityLoaded={!!activity.data}+ detail={detail}+ deviceId={deviceId}+ workingDirectory={workingDirectory}+ onAction={actions.run}+ />+ <Sections+ activity={activity}+ busy={actions.busy}+ detail={detail}+ onAction={actions.run}+ onOpenTab={onOpenTab}+ />+ </ScrollArea>+ <MergeDock+ busy={actions.busy}+ contextLoading={context === undefined}+ detail={detail}+ error={actions.error}+ local={local}+ onAction={actions.run}+ onDismissError={actions.dismissError}+ onPush={actions.push}+ onRetry={actions.retry}+ />+ </Flexbox>+ );+ },+);++PullRequest.displayName = 'PullRequestPane';++export default PullRequest;diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts b/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.tsnew file mode 100644index 00000000000..63c8abe8ef2--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/mergeDockData.ts@@ -0,0 +1,363 @@+import type { DeviceGitPullRequestDetail, DeviceGitPullRequestMergeMethod } from '@lobechat/types';++export type Tone = 'success' | 'warning' | 'error' | 'neutral' | 'merged';++export type ChecksStatus = 'success' | 'pending' | 'failure' | 'unstable';++export type DockIcon =+ 'check' | 'x' | 'eye' | 'spinner' | 'conflict' | 'behind' | 'push' | 'shieldAlert' | 'merge';++export interface DockText {+ labelKey: string;+ labelParams?: Record<string, string | number>;+}++export interface DockStatus extends DockText {+ icon: DockIcon;+ key:+ | 'merged'+ | 'closed'+ | 'draft'+ | 'calculating'+ | 'conflicts'+ | 'blocked'+ | 'waiting'+ | 'autoMerge'+ | 'bypass'+ | 'ready'+ | 'error';+ tone: Tone;+}++export type DockAction =+ | {+ admin: boolean;+ busy?: boolean;+ busyLabelKey?: string;+ kind: 'merge';+ method: DeviceGitPullRequestMergeMethod;+ tone: 'success' | 'plain' | 'error';+ }+ | {+ busy?: boolean;+ busyLabelKey?: string;+ kind: 'autoMerge';+ method: DeviceGitPullRequestMergeMethod;+ tone: 'plain';+ }+ | { busy?: boolean; busyLabelKey?: string; kind: 'updateBranch'; tone: 'success' }+ | { busy?: boolean; busyLabelKey?: string; kind: 'ready' }+ | { busy?: boolean; busyLabelKey?: string; kind: 'deleteBranch' }+ | { busy?: boolean; busyLabelKey?: string; kind: 'reopen' }+ | { kind: 'disabled'; labelKey: string };++export interface MergeDockModel {+ action?: DockAction;+ bypassAvailable: boolean;+ checksStatus: ChecksStatus;+ hintKey?: string;+ hintParams?: Record<string, string | number>;+ reasons: DockText[];+ showPush?: boolean;+ showUpdateBranch: boolean;+ status: DockStatus;+}++export interface MergeDockInput {+ detail: DeviceGitPullRequestDetail;+ local?: { ahead: number };+ ui: {+ bypass: boolean;+ busy?: 'merge' | 'update' | 'push' | 'ready' | 'autoMerge';+ contextLoading?: boolean;+ error?: string;+ method: DeviceGitPullRequestMergeMethod;+ };+}++export const PR_KEYS = {+ action: {+ arming: 'workingPanel.pr.action.arming',+ calculating: 'workingPanel.pr.action.calculating',+ conflicting: 'workingPanel.pr.action.conflicting',+ merging: 'workingPanel.pr.action.merging',+ pushing: 'workingPanel.pr.action.pushing',+ readying: 'workingPanel.pr.action.readying',+ updating: 'workingPanel.pr.action.updating',+ waiting: 'workingPanel.pr.action.waiting',+ },+ hint: {+ autoMerge: 'workingPanel.pr.hint.autoMerge',+ blocked: 'workingPanel.pr.hint.blocked',+ bypass: 'workingPanel.pr.hint.bypass',+ calculating: 'workingPanel.pr.hint.calculating',+ merge: 'workingPanel.pr.hint.merge',+ merged: 'workingPanel.pr.hint.merged',+ readOnly: 'workingPanel.pr.hint.readOnly',+ },+ method: {+ merge: 'workingPanel.pr.method.merge',+ rebase: 'workingPanel.pr.method.rebase',+ squash: 'workingPanel.pr.method.squash',+ },+ reason: {+ behind: 'workingPanel.pr.reason.behind',+ changesRequested: 'workingPanel.pr.reason.changesRequested',+ checksFailing: 'workingPanel.pr.reason.checksFailing',+ checksPending: 'workingPanel.pr.reason.checksPending',+ conflicts: 'workingPanel.pr.reason.conflicts',+ optionalFailing: 'workingPanel.pr.reason.optionalFailing',+ reviewRequired: 'workingPanel.pr.reason.reviewRequired',+ rules: 'workingPanel.pr.reason.rules',+ },+ status: {+ autoMerge: 'workingPanel.pr.status.autoMerge',+ blocked: 'workingPanel.pr.status.blocked',+ bypass: 'workingPanel.pr.status.bypass',+ calculating: 'workingPanel.pr.status.calculating',+ closed: 'workingPanel.pr.status.closed',+ conflicts: 'workingPanel.pr.status.conflicts',+ draft: 'workingPanel.pr.status.draft',+ error: 'workingPanel.pr.status.error',+ merged: 'workingPanel.pr.status.merged',+ ready: 'workingPanel.pr.status.ready',+ waiting: 'workingPanel.pr.status.waiting',+ },+} as const;++const BLOCKED_STATES = new Set(['BLOCKED', 'DIRTY', 'BEHIND']);++const computeChecksStatus = (checks: DeviceGitPullRequestDetail['checks']): ChecksStatus => {+ if (+ checks.some(+ (check) => check.required && (check.status === 'failure' || check.status === 'cancelled'),+ )+ )+ return 'failure';+ if (checks.some((check) => check.status === 'pending')) return 'pending';+ if (+ checks.some(+ (check) => !check.required && (check.status === 'failure' || check.status === 'cancelled'),+ )+ )+ return 'unstable';+ return 'success';+};++const countFailing = (checks: DeviceGitPullRequestDetail['checks'], required: boolean) =>+ checks.filter(+ (check) =>+ check.required === required && (check.status === 'failure' || check.status === 'cancelled'),+ ).length;++const buildReasons = (+ detail: DeviceGitPullRequestDetail,+ checksStatus: ChecksStatus,+): { blockers: DockText[]; reasons: DockText[] } => {+ const blockers: DockText[] = [];+ const reasons: DockText[] = [];++ if (checksStatus === 'failure')+ blockers.push({+ labelKey: PR_KEYS.reason.checksFailing,+ labelParams: { count: countFailing(detail.checks, true) },+ });+ if (detail.reviewDecision === 'CHANGES_REQUESTED')+ blockers.push({+ labelKey: PR_KEYS.reason.changesRequested,+ labelParams: {+ authors: detail.reviews+ .filter((review) => review.state === 'CHANGES_REQUESTED')+ .map((review) => review.author)+ .join(', '),+ },+ });+ if (detail.reviewDecision === 'REVIEW_REQUIRED')+ blockers.push({ labelKey: PR_KEYS.reason.reviewRequired });+ if (detail.mergeStateStatus === 'BEHIND')+ blockers.push({ labelKey: PR_KEYS.reason.behind, labelParams: { base: detail.baseRefName } });+ if (checksStatus === 'pending') reasons.push({ labelKey: PR_KEYS.reason.checksPending });+ if (checksStatus === 'unstable')+ reasons.push({+ labelKey: PR_KEYS.reason.optionalFailing,+ labelParams: { count: countFailing(detail.checks, false) },+ });++ return { blockers, reasons };+};++const buildStatus = (+ detail: DeviceGitPullRequestDetail,+ ui: MergeDockInput['ui'],+ checksStatus: ChecksStatus,+ blocked: boolean,+ hasBlockers: boolean,+): DockStatus => {+ if (ui.error)+ return {+ icon: 'x',+ key: 'error',+ labelKey: PR_KEYS.status.error,+ labelParams: { message: ui.error },+ tone: 'error',+ };+ if (detail.state === 'merged')+ return { icon: 'merge', key: 'merged', labelKey: PR_KEYS.status.merged, tone: 'merged' };+ if (detail.state === 'closed')+ return { icon: 'x', key: 'closed', labelKey: PR_KEYS.status.closed, tone: 'error' };+ if (detail.isDraft)+ return { icon: 'eye', key: 'draft', labelKey: PR_KEYS.status.draft, tone: 'neutral' };+ if (detail.mergeable === 'UNKNOWN' || ui.contextLoading)+ return {+ icon: 'spinner',+ key: 'calculating',+ labelKey: PR_KEYS.status.calculating,+ tone: 'neutral',+ };+ if (detail.mergeable === 'CONFLICTING')+ return {+ icon: 'conflict',+ key: 'conflicts',+ labelKey: PR_KEYS.status.conflicts,+ labelParams: { base: detail.baseRefName },+ tone: 'error',+ };+ if (ui.bypass)+ return { icon: 'shieldAlert', key: 'bypass', labelKey: PR_KEYS.status.bypass, tone: 'error' };+ if (detail.autoMerge)+ return {+ icon: 'merge',+ key: 'autoMerge',+ labelKey: PR_KEYS.status.autoMerge,+ labelParams: { method: detail.autoMerge.method },+ tone: 'merged',+ };+ if (hasBlockers || (blocked && checksStatus !== 'pending'))+ return { icon: 'x', key: 'blocked', labelKey: PR_KEYS.status.blocked, tone: 'error' };+ if (checksStatus === 'pending')+ return { icon: 'spinner', key: 'waiting', labelKey: PR_KEYS.status.waiting, tone: 'warning' };+ return { icon: 'check', key: 'ready', labelKey: PR_KEYS.status.ready, tone: 'success' };+};++const BUSY_LABEL_KEY: Record<NonNullable<MergeDockInput['ui']['busy']>, string> = {+ autoMerge: PR_KEYS.action.arming,+ merge: PR_KEYS.action.merging,+ push: PR_KEYS.action.pushing,+ ready: PR_KEYS.action.readying,+ update: PR_KEYS.action.updating,+};++export const resolveMergeDock = ({ detail, local, ui }: MergeDockInput): MergeDockModel => {+ const checksStatus = computeChecksStatus(detail.checks);+ const blocked = BLOCKED_STATES.has(detail.mergeStateStatus);+ const canAutoMerge =+ checksStatus === 'pending' &&+ detail.mergeable === 'MERGEABLE' &&+ detail.reviewDecision !== 'CHANGES_REQUESTED' &&+ !detail.autoMerge;++ const settled =+ !ui.contextLoading &&+ detail.state === 'open' &&+ !detail.isDraft &&+ detail.mergeable !== 'UNKNOWN';+ const { blockers, reasons: softReasons } = settled+ ? buildReasons(detail, checksStatus)+ : { blockers: [], reasons: [] };+ if (settled && blocked && blockers.length === 0 && checksStatus !== 'pending' && !ui.bypass)+ blockers.push({ labelKey: PR_KEYS.reason.rules });+ const reasons = detail.mergeable === 'CONFLICTING' ? softReasons : [...blockers, ...softReasons];+ const status = buildStatus(detail, ui, checksStatus, blocked, blockers.length > 0);++ let action: DockAction | undefined;+ if (ui.contextLoading) {+ action =+ detail.state === 'open'+ ? { kind: 'disabled', labelKey: PR_KEYS.action.calculating }+ : undefined;+ } else if (!detail.viewerCanWrite) {+ action = undefined;+ } else if (detail.state === 'merged') {+ action = detail.isCrossRepository ? undefined : { kind: 'deleteBranch' };+ } else if (detail.state === 'closed') {+ action = { kind: 'reopen' };+ } else if (detail.isDraft) {+ action = { kind: 'ready' };+ } else if (detail.mergeable === 'UNKNOWN') {+ action = { kind: 'disabled', labelKey: PR_KEYS.action.calculating };+ } else if (detail.mergeable === 'CONFLICTING') {+ action = { kind: 'disabled', labelKey: PR_KEYS.action.conflicting };+ } else if (detail.mergeStateStatus === 'BEHIND' && !ui.bypass) {+ action = { kind: 'updateBranch', tone: 'success' };+ } else if (blocked && !ui.bypass) {+ if (canAutoMerge) action = { kind: 'autoMerge', method: ui.method, tone: 'plain' };+ else if (detail.autoMerge) action = { kind: 'disabled', labelKey: PR_KEYS.action.waiting };+ else action = { kind: 'disabled', labelKey: PR_KEYS.method[ui.method] };+ } else {+ action = {+ admin: ui.bypass,+ kind: 'merge',+ method: ui.method,+ tone: ui.bypass ? 'error' : checksStatus === 'success' ? 'success' : 'plain',+ };+ }++ if (action && action.kind !== 'disabled' && ui.busy) {+ action = { ...action, busy: true, busyLabelKey: BUSY_LABEL_KEY[ui.busy] };+ }++ const bypassAvailable =+ detail.viewerCanWrite &&+ detail.viewerCanBypass &&+ blocked &&+ detail.state === 'open' &&+ !detail.isDraft;+ const showPush = (local?.ahead ?? 0) > 0 && action?.kind === 'merge';+ const showUpdateBranch =+ settled &&+ detail.viewerCanWrite &&+ detail.baseBehindBy > 0 &&+ detail.mergeable !== 'CONFLICTING' &&+ action?.kind !== 'updateBranch';++ let hintKey: string | undefined;+ let hintParams: Record<string, string | number> | undefined;++ if (ui.contextLoading) {+ hintKey = undefined;+ } else if (!detail.viewerCanWrite && detail.state === 'open') {+ hintKey = PR_KEYS.hint.readOnly;+ hintParams = { repo: `${detail.repo.owner}/${detail.repo.name}` };+ } else if (ui.error) {+ hintKey = undefined;+ } else if (detail.mergeable === 'UNKNOWN') {+ hintKey = PR_KEYS.hint.calculating;+ } else if (ui.bypass) {+ hintKey = PR_KEYS.hint.bypass;+ } else if (detail.autoMerge) {+ hintKey = PR_KEYS.hint.autoMerge;+ hintParams = { method: detail.autoMerge.method };+ } else if (blocked && !canAutoMerge) {+ hintKey = PR_KEYS.hint.blocked;+ } else if (action?.kind === 'merge') {+ hintKey = PR_KEYS.hint.merge;+ hintParams = { base: detail.baseRefName, count: detail.commits.length };+ } else if (detail.state === 'merged') {+ hintKey = PR_KEYS.hint.merged;+ hintParams = { head: detail.headRefName };+ }++ if (reasons.length > 0 && hintKey !== PR_KEYS.hint.readOnly) hintKey = undefined;++ return {+ action,+ bypassAvailable,+ checksStatus,+ hintKey,+ hintParams,+ reasons,+ showPush,+ showUpdateBranch,+ status,+ };+};diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/mergeMethodStorage.ts b/src/features/Conversation/WorkingSidebar/PullRequest/mergeMethodStorage.tsnew file mode 100644index 00000000000..c4dc2bd358d--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/mergeMethodStorage.ts@@ -0,0 +1,24 @@+import type { DeviceGitPullRequestMergeMethod } from '@lobechat/types';++export const MERGE_METHOD_STORAGE_KEY = 'lobechat-pr-merge-method';+export const MERGE_METHODS: DeviceGitPullRequestMergeMethod[] = ['squash', 'merge', 'rebase'];++const isMergeMethod = (value: unknown): value is DeviceGitPullRequestMergeMethod =>+ MERGE_METHODS.includes(value as DeviceGitPullRequestMergeMethod);++export const readMergeMethod = (): DeviceGitPullRequestMergeMethod => {+ try {+ const raw = window.localStorage.getItem(MERGE_METHOD_STORAGE_KEY);+ return isMergeMethod(raw) ? raw : 'squash';+ } catch {+ return 'squash';+ }+};++export const writeMergeMethod = (method: DeviceGitPullRequestMergeMethod) => {+ try {+ window.localStorage.setItem(MERGE_METHOD_STORAGE_KEY, method);+ } catch {+ return;+ }+};diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/prVisual.ts b/src/features/Conversation/WorkingSidebar/PullRequest/prVisual.tsnew file mode 100644index 00000000000..9c0edda95f4--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/prVisual.ts@@ -0,0 +1,96 @@+import type { DeviceGitPullRequestCheck, DeviceGitPullRequestDetail } from '@lobechat/types';+import { cssVar } from 'antd-style';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import type { LucideIcon } from 'lucide-react';+import {+ ArrowUpIcon,+ CheckIcon,+ CircleCheckIcon,+ CircleSlashIcon,+ CircleXIcon,+ EyeIcon,+ GitMergeIcon,+ GitPullRequestDraftIcon,+ LoaderCircleIcon,+ RefreshCwIcon,+ ShieldAlertIcon,+ TriangleAlertIcon,+} from 'lucide-react';++import {+ getPullRequestState,+ MERGED_PURPLE,+ PR_STATE_VISUAL,+} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';++import type { DockIcon, Tone } from './mergeDockData';++dayjs.extend(relativeTime);++export type TranslateKey = (key: string, params?: Record<string, string | number>) => string;++export const TONE_COLOR: Record<Tone, string> = {+ error: cssVar.colorError,+ merged: MERGED_PURPLE,+ neutral: cssVar.colorTextTertiary,+ success: cssVar.colorSuccess,+ warning: cssVar.colorWarning,+};++export const DOCK_ICON: Record<DockIcon, LucideIcon> = {+ behind: RefreshCwIcon,+ check: CheckIcon,+ conflict: TriangleAlertIcon,+ eye: EyeIcon,+ merge: GitMergeIcon,+ push: ArrowUpIcon,+ shieldAlert: ShieldAlertIcon,+ spinner: LoaderCircleIcon,+ x: CircleXIcon,+};++export type PullRequestVisualState = 'closed' | 'draft' | 'merged' | 'open';++export const getDetailVisual = (detail: DeviceGitPullRequestDetail) => {+ const state = getPullRequestState(detail);+ if (state === 'open' && detail.isDraft)+ return {+ color: cssVar.colorTextTertiary,+ icon: GitPullRequestDraftIcon,+ state: 'draft' as PullRequestVisualState,+ };+ return { ...PR_STATE_VISUAL[state], state: state as PullRequestVisualState };+};++export const getCheckVisual = (+ status: DeviceGitPullRequestCheck['status'],+): { icon: LucideIcon; spin?: boolean; tone: Tone } => {+ switch (status) {+ case 'pending': {+ return { icon: LoaderCircleIcon, spin: true, tone: 'warning' };+ }+ case 'failure':+ case 'cancelled': {+ return { icon: CircleXIcon, tone: 'error' };+ }+ case 'success': {+ return { icon: CircleCheckIcon, tone: 'success' };+ }+ default: {+ return { icon: CircleSlashIcon, tone: 'neutral' };+ }+ }+};++export const formatCheckDuration = (check: DeviceGitPullRequestCheck) => {+ if (!check.startedAt) return undefined;+ const seconds = Math.max(+ 0,+ dayjs(check.completedAt ?? undefined).diff(check.startedAt, 'second'),+ );+ const minutes = Math.floor(seconds / 60);+ return minutes > 0 ? `${minutes}m ${String(seconds % 60).padStart(2, '0')}s` : `${seconds}s`;+};++export const timeAgo = (iso: string) => dayjs(iso).fromNow(true);diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.tsnew file mode 100644index 00000000000..93febf1406b--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts@@ -0,0 +1,107 @@+import type { DeviceGitPullRequestAction, DeviceGitPullRequestActionResult } from '@lobechat/types';+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useRef, useState } from 'react';++import { mutate } from '@/libs/swr';+import { deviceKeys } from '@/libs/swr/keys';+import { gitService } from '@/services/git';++export type PullRequestBusy = DeviceGitPullRequestAction['type'] | 'push';++const DOCK_KINDS = new Set<PullRequestBusy>([+ 'autoMerge',+ 'merge',+ 'push',+ 'ready',+ 'updateBranch',+]);++interface UsePullRequestActionsParams {+ deviceId?: string;+ mutateDetail: () => Promise<unknown>;+ number: number;+ workingDirectory: string;+}++export const usePullRequestActions = ({+ deviceId,+ mutateDetail,+ number,+ workingDirectory,+}: UsePullRequestActionsParams) => {+ const [busy, setBusy] = useState<PullRequestBusy>();+ const [error, setError] = useState<string>();+ const busyRef = useRef(false);+ const retryRef = useRef<() => Promise<boolean>>(undefined);++ const perform = useCallback(+ async (kind: PullRequestBusy, request: () => Promise<DeviceGitPullRequestActionResult>) => {+ if (busyRef.current) return false;+ busyRef.current = true;+ setBusy(kind);+ const isDockAction = DOCK_KINDS.has(kind);+ if (isDockAction) setError(undefined);+ const fail = (message: string) => {+ if (isDockAction) {+ setError(message);+ retryRef.current = () => perform(kind, request);+ } else {+ toast.error(message);+ }+ return false;+ };+ try {+ const result = await request();+ if (!result.success) return fail(result.error || 'unknown error');+ const cacheDeviceId = deviceId ?? 'local';+ await Promise.all([+ mutateDetail(),+ mutate(deviceKeys.gitPullRequestActivity(cacheDeviceId, workingDirectory, number)),+ mutate(+ (key: unknown) =>+ Array.isArray(key) &&+ key[0] === deviceKeys.gitLinkedPR.root &&+ key[1] === cacheDeviceId &&+ key[2] === workingDirectory,+ ),+ mutate(+ (key: unknown) =>+ Array.isArray(key) &&+ key[0] === deviceKeys.gitPullRequestMergeContext.root &&+ key[1] === cacheDeviceId &&+ key[2] === workingDirectory &&+ key[3] === number,+ ),+ mutate(deviceKeys.gitAheadBehind(cacheDeviceId, workingDirectory)),+ mutate(deviceKeys.gitWorkingTreeStatus(cacheDeviceId, workingDirectory)),+ ]);+ return true;+ } catch (err) {+ return fail(err instanceof Error ? err.message : String(err));+ } finally {+ busyRef.current = false;+ setBusy(undefined);+ }+ },+ [deviceId, mutateDetail, number, workingDirectory],+ );++ const run = useCallback(+ (action: DeviceGitPullRequestAction) =>+ perform(action.type, () =>+ gitService.runPullRequestAction({ action, deviceId, number, path: workingDirectory }),+ ),+ [deviceId, number, perform, workingDirectory],+ );++ const push = useCallback(+ () => perform('push', () => gitService.pushGitBranch({ deviceId, path: workingDirectory })),+ [deviceId, perform, workingDirectory],+ );++ const retry = useCallback(() => void retryRef.current?.(), []);++ const dismissError = useCallback(() => setError(undefined), []);++ return { busy, dismissError, error, push, retry, run };+};diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 4edba46b457..7df7ebbfdf6 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -40,6 +40,40 @@ const effectiveConfig = vi.hoisted(() => ({}));const platform = vi.hoisted(() => ({ isDesktop: true }));+const linkedPR = vi.hoisted(() => ({+ number: undefined as number | undefined,+ branch: 'feature' as string | undefined,+ status: undefined as string | undefined,+}));++vi.mock('@/store/device', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useFetchGitBranch: () => ({ data: linkedPR.branch ? { branch: linkedPR.branch } : undefined }),+ useFetchGitLinkedPR: () => ({+ data: {+ pullRequestStatus: linkedPR.status,+ pullRequest: linkedPR.number+ ? { number: linkedPR.number, state: 'open', url: 'https://github.com/test/repo/pull/1' }+ : undefined,+ },+ }),+}));++vi.mock('../PullRequest', async () => {+ const { useState } = await import('react');+ return {+ default: function PullRequestDraft() {+ const [draft, setDraft] = useState('');+ return (+ <input+ aria-label="PR draft"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ );+ },+ };+});const filesProps = vi.hoisted(() => ({current: undefined as { deviceId?: string; workingDirectory: string } | undefined,@@ -96,6 +130,7 @@ const chatStore = vi.hoisted(() => ({threadMaps: {} as Record<string, any[]>,// read by the real topicSelectors.currentTopicMetadata (sourcePath resolution)topicDataMap: {} as Record<string, unknown>,+ topicDetailMap: {} as Record<string, unknown>,}));const globalStore = vi.hoisted(() => ({@@ -384,6 +419,11 @@ beforeEach(() => {effectiveConfig.agencyConfig = undefined;effectiveConfig.workspaceScoped = false;platform.isDesktop = true;+ linkedPR.number = undefined;+ linkedPR.branch = 'feature';+ linkedPR.status = undefined;+ chatStore.topicDataMap = {};+ chatStore.topicDetailMap = {};filesProps.current = undefined;renderedReview.current = undefined;reviewState.repoType = undefined;@@ -411,6 +451,90 @@ afterEach(() => {});describe('AgentWorkingSidebar — controlled panel width', () => {+ it('opens a scoped saved PR before branch lookup and discards it after authoritative empty lookup', () => {+ linkedPR.branch = undefined;+ reviewState.workingDirectory = '/repo';+ chatStore.activeTopicId = 'topic-pr';+ chatStore.topicDetailMap = {+ 'topic-pr': {+ id: 'topic-pr',+ metadata: {+ workingDirectoryConfig: {+ path: '/repo',+ git: {+ branch: 'feature',+ github: {+ pullRequest: {+ number: 42,+ title: 'Saved PR',+ state: 'open',+ url: 'https://github.com/test/repo/pull/42',+ },+ },+ },+ },+ },+ },+ };+ globalStore.status.workingSidebarTab = 'pr';+ localStorageState.openTabsByContext = { 'topic:topic-pr': ['pr'] };+ const { rerender } = render(<AgentWorkingSidebar />);+ expect(screen.getByRole('textbox', { name: 'PR draft' })).toBeInTheDocument();+ linkedPR.status = 'ok';+ rerender(<AgentWorkingSidebar availableWidth={1200} />);+ expect(screen.queryByRole('textbox', { name: 'PR draft' })).not.toBeInTheDocument();+ });++ it.each([+ { path: '/other', boundDeviceId: undefined },+ { path: '/repo', boundDeviceId: 'other-device' },+ ])('does not bootstrap a snapshot from another scope: %o', ({ path, boundDeviceId }) => {+ linkedPR.branch = undefined;+ reviewState.workingDirectory = '/repo';+ chatStore.activeTopicId = 'topic-pr';+ chatStore.topicDetailMap = {+ 'topic-pr': {+ id: 'topic-pr',+ metadata: {+ boundDeviceId,+ workingDirectoryConfig: {+ path,+ git: {+ github: {+ pullRequest: {+ number: 42,+ state: 'open',+ title: 'Other PR',+ url: 'https://github.com/test/repo/pull/42',+ },+ },+ },+ },+ },+ },+ };+ globalStore.status.workingSidebarTab = 'pr';+ localStorageState.openTabsByContext = { 'topic:topic-pr': ['pr'] };+ render(<AgentWorkingSidebar />);+ expect(screen.queryByRole('textbox', { name: 'PR draft' })).not.toBeInTheDocument();+ });++ it('resets PR state when the PR number or directory changes', () => {+ reviewState.repoType = 'github';+ reviewState.workingDirectory = '/repo';+ linkedPR.number = 1;+ globalStore.status.workingSidebarTab = 'pr';+ localStorageState.openTabsByContext = { 'draft:default:none': ['pr'] };+ const { rerender } = render(<AgentWorkingSidebar />);+ fireEvent.change(screen.getByLabelText('PR draft'), { target: { value: 'old draft' } });+ linkedPR.number = 2;+ rerender(<AgentWorkingSidebar availableWidth={1600} />);+ expect(screen.getByLabelText('PR draft')).toHaveValue('');+ fireEvent.change(screen.getByLabelText('PR draft'), { target: { value: 'another draft' } });+ reviewState.workingDirectory = '/other';+ rerender(<AgentWorkingSidebar availableWidth={1601} />);+ expect(screen.getByLabelText('PR draft')).toHaveValue('');+ });it('seeds the RightPanel with the default width', () => {render(<AgentWorkingSidebar />);diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 249b36e6075..b8e3b48f1bf 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -43,6 +43,10 @@ import { useBusinessWorkingSidebarTabs } from '@/business/client/features/Workinimport { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import { isDesktop } from '@/const/version';+import {+ getPullRequestState,+ PR_STATE_VISUAL,+} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { getPortalViewWidth } from '@/features/Portal/portalWidth';@@ -63,7 +67,12 @@ import { useChatStore } from '@/store/chat';import { chatPortalSelectors, portalThreadSelectors, topicSelectors } from '@/store/chat/selectors';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import { deviceSelectors, useDeviceStore } from '@/store/device';+import {+ deviceSelectors,+ useDeviceStore,+ useFetchGitBranch,+ useFetchGitLinkedPR,+} from '@/store/device';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -73,6 +82,7 @@ import Files from './Files';import { sidebarWidthBudget } from './fitsBesidePortal';import Overview from './Overview';import OverviewSlot from './OverviewSlot';+import PullRequest from './PullRequest';import ResourcesSection from './ResourcesSection';import Review from './Review';import WorkspaceTab from './WorkspaceTab';@@ -326,6 +336,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })const topicWorkingDirectoryConfig = useChatStore((s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,);+ const topicDeviceId = useChatStore((s) => topicSelectors.currentTopicMetadata(s)?.boundDeviceId);const deviceDirs = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(targetDeviceId));const sourceWorkingDirectory = useMemo(() => {if (!workingDirectory) return undefined;@@ -369,6 +380,33 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })// directory is irrelevant to the user, so hide the tab even when one resolves.const filesAvailable = !isChatMode && (isLocalExecution || isDeviceMode) && !!workingDirectory;const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;+ const snapshotConfig =+ (topicDeviceId ? topicDeviceId === targetDeviceId : isLocalExecution) &&+ getWorkingDirEffectivePath(topicWorkingDirectoryConfig) === workingDirectory+ ? topicWorkingDirectoryConfig+ : deviceDirs.find((entry) => getWorkingDirEffectivePath(entry) === workingDirectory);+ const isGithub =+ repoType === 'github' || (!repoType && !!snapshotConfig?.git?.github?.pullRequest);+ const gitPath = filesystemEnvironmentAvailable && isGithub ? workingDirectory : undefined;+ const { data: branchData } = useFetchGitBranch(remoteDeviceId, gitPath);+ const { data: linkedPR } = useFetchGitLinkedPR(+ remoteDeviceId,+ gitPath,+ branchData?.branch,+ isGithub,+ );+ const snapshotPR =+ !branchData || (snapshotConfig?.git?.branch === branchData.branch && !branchData.detached)+ ? snapshotConfig?.git?.github?.pullRequest+ : undefined;+ // A settled empty lookup supersedes the snapshot; failures may keep displaying it.+ const pullRequest =+ filesystemEnvironmentAvailable && workingDirectory+ ? linkedPR?.pullRequestStatus === 'ok'+ ? linkedPR.pullRequest+ : (linkedPR?.pullRequest ?? snapshotPR)+ : undefined;+ const prAvailable = !!pullRequest;const paramsAvailable = !isHetero;// The in-app browser pages are renderer-retained Electron webviews — desktop only.const browserAvailable = isDesktop;@@ -415,6 +453,15 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })...(reviewAvailable? [{ icon: ClipboardListIcon, key: 'review', label: t('workingPanel.review.title') }]: []),+ ...(pullRequest+ ? [+ {+ icon: PR_STATE_VISUAL[getPullRequestState(pullRequest)].icon,+ key: 'pr',+ label: `#${pullRequest.number}`,+ },+ ]+ : []),...(filesAvailable? [{ icon: FilesIcon, key: 'files', label: t('workingPanel.files.title') }]: []),@@ -443,6 +490,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })filesAvailable,isHetero,paramsAvailable,+ pullRequest,reviewAvailable,t,],@@ -870,6 +918,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })const workspaceGroup = group('workspace', t('workingPanel.openMenu.workspace'), ['review',+ 'pr','files','works','comments',@@ -943,6 +992,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })agentId={activeAgentId}deviceId={remoteDeviceId}environmentAvailable={filesystemEnvironmentAvailable}+ prAvailable={prAvailable}repoType={environmentRepoType}sourcePath={sourceWorkingDirectory}workingDirectory={environmentWorkingDirectory}@@ -1061,6 +1111,22 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })/></Flexbox>)}+ {pullRequest && workingDirectory && (+ <Activity mode={showRightPanel && activeTab === 'pr' ? 'visible' : 'hidden'}>+ <Flexbox className={styles.pane}>+ <PullRequest+ active={!!showRightPanel && activeTab === 'pr'}+ deviceId={remoteDeviceId}+ key={JSON.stringify([remoteDeviceId, workingDirectory, pullRequest.number])}+ number={pullRequest.number}+ summary={pullRequest}+ url={pullRequest.url}+ workingDirectory={workingDirectory}+ onOpenTab={openTab}+ />+ </Flexbox>+ </Activity>+ )}{filesAvailable && (<Activity mode={showRightPanel && activeTab === 'files' ? 'visible' : 'hidden'}><Flexbox className={styles.pane}>diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex f07f8b206b1..99528646697 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -867,6 +867,35 @@ export const deviceKeys = {...(pullRequestNumber === undefined ? [] : [pullRequestNumber]),],),+ gitPullRequestDetail: def(+ 'device:gitPullRequestDetail',+ (deviceId: string, path: string, number: number) => [+ 'device:gitPullRequestDetail',+ deviceId,+ path,+ number,+ ],+ ),+ gitPullRequestActivity: def(+ 'device:gitPullRequestActivity',+ (deviceId: string, path: string, number: number) => [+ 'device:gitPullRequestActivity',+ deviceId,+ path,+ number,+ ],+ ),+ gitPullRequestMergeContext: def(+ 'device:gitPullRequestMergeContext',+ (deviceId: string, path: string, number: number, headRefOid?: string, baseRefName?: string) => [+ 'device:gitPullRequestMergeContext',+ deviceId,+ path,+ number,+ ...(headRefOid === undefined ? [] : [headRefOid]),+ ...(baseRefName === undefined ? [] : [baseRefName]),+ ],+ ),gitRemoteBranches: def('device:gitRemoteBranches', (deviceId: string, dirPath: string) => ['device:gitRemoteBranches',deviceId,diff --git a/src/services/electron/git.ts b/src/services/electron/git.tsindex 1dd6b7b9049..2c9dda3a698 100644--- a/src/services/electron/git.ts+++ b/src/services/electron/git.ts@@ -9,6 +9,11 @@ import {type GitDeleteBranchResult,type GitFileRevertResult,type GitLinkedPullRequestResult,+ type GitPullRequestAction,+ type GitPullRequestActionResult,+ type GitPullRequestActivity,+ type GitPullRequestDetailResult,+ type GitPullRequestMergeContext,type GitPullResult,type GitPushResult,type GitRemoteBranchListItem,@@ -48,6 +53,39 @@ class ElectronGitService {return this.ipc.git.getLinkedPullRequest(params);}+ async getPullRequestDetail(params: {+ coreOnly?: boolean;+ number: number;+ path: string;+ }): Promise<GitPullRequestDetailResult> {+ return this.ipc.git.getPullRequestDetail(params);+ }++ async getPullRequestActivity(params: {+ number: number;+ path: string;+ }): Promise<GitPullRequestActivity> {+ return this.ipc.git.getPullRequestActivity(params);+ }++ async getPullRequestMergeContext(params: {+ baseRefName: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ }): Promise<GitPullRequestMergeContext> {+ return this.ipc.git.getPullRequestMergeContext(params);+ }++ async runPullRequestAction(params: {+ action: GitPullRequestAction;+ number: number;+ path: string;+ }): Promise<GitPullRequestActionResult> {+ return this.ipc.git.runPullRequestAction(params);+ }+async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {return this.ipc.git.listGitBranches(dirPath);}diff --git a/src/services/git.ts b/src/services/git.tsindex 30ea5a70fe9..ac4031f5d05 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -13,6 +13,11 @@ import type {DeviceGitDeleteBranchResult,DeviceGitLinkedPullRequest,DeviceGitLinkedPullRequestLookupStatus,+ DeviceGitPullRequestAction,+ DeviceGitPullRequestActionResult,+ DeviceGitPullRequestActivity,+ DeviceGitPullRequestDetailResult,+ DeviceGitPullRequestMergeContext,DeviceGitRemoveWorktreeResult,DeviceGitRenameBranchResult,DeviceGitSyncResult,@@ -231,6 +236,80 @@ class GitService {};}+ /** Full detail of a pull request in a working directory. */+ async getPullRequestDetail({+ coreOnly,+ deviceId,+ number,+ path,+ }: {+ coreOnly?: boolean;+ deviceId?: string;+ number: number;+ path: string;+ }): Promise<DeviceGitPullRequestDetailResult> {+ return deviceId+ ? ((await lambdaClient.device.gitPullRequestDetail.query({+ coreOnly,+ deviceId,+ number,+ path,+ })) ?? {+ detail: null,+ status: 'error',+ })+ : electronGitService.getPullRequestDetail({ coreOnly, number, path });+ }++ async getPullRequestActivity(params: {+ deviceId?: string;+ number: number;+ path: string;+ }): Promise<DeviceGitPullRequestActivity> {+ if (!params.deviceId) return electronGitService.getPullRequestActivity(params);+ const result = await lambdaClient.device.gitPullRequestActivity.query({+ ...params,+ deviceId: params.deviceId,+ });+ if (!result) throw new Error('Unable to load pull request activity');+ return result;+ }++ /** Branch protection, viewer permission and base drift for a pull request. */+ async getPullRequestMergeContext({+ deviceId,+ ...params+ }: {+ baseRefName: string;+ deviceId?: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ }): Promise<DeviceGitPullRequestMergeContext | null> {+ return deviceId+ ? ((await lambdaClient.device.gitPullRequestMergeContext.query({ deviceId, ...params })) ??+ null)+ : electronGitService.getPullRequestMergeContext(params);+ }++ /** Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a pull request. */+ async runPullRequestAction({+ action,+ deviceId,+ number,+ path,+ }: {+ action: DeviceGitPullRequestAction;+ deviceId?: string;+ number: number;+ path: string;+ }): Promise<DeviceGitPullRequestActionResult> {+ return deviceId+ ? lambdaClient.device.runGitPullRequestAction.mutate({ action, deviceId, number, path })+ : electronGitService.runPullRequestAction({ action, number, path });+ }+/** Working-tree dirty-file counts for a working directory. */async getGitWorkingTreeStatus({deviceId,diff --git a/src/store/device/gitHooks.test.ts b/src/store/device/gitHooks.test.tsnew file mode 100644index 00000000000..b213f581bfd--- /dev/null+++ b/src/store/device/gitHooks.test.ts@@ -0,0 +1,169 @@+import type { DeviceGitPullRequestDetailResult } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { gitService } from '@/services/git';++import {+ pullRequestDetailRefreshInterval,+ useFetchGitPullRequestActivity,+ useFetchGitPullRequestDetail,+ useFetchGitPullRequestMergeContext,+} from './gitHooks';++const detailResult = (+ overrides: Partial<DeviceGitPullRequestDetailResult['detail']> = {},+): DeviceGitPullRequestDetailResult => ({+ detail: {+ additions: 0,+ author: 'octocat',+ baseBehindBy: 0,+ baseRefName: 'main',+ body: '',+ changedFiles: 0,+ checks: [],+ comments: [],+ commits: [],+ deletions: 0,+ headRefName: 'feature',+ headRefOid: 'a'.repeat(40),+ isCrossRepository: false,+ isDraft: false,+ mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN',+ number: 1,+ repo: { name: 'repo', owner: 'octocat' },+ reviewDecision: null,+ reviews: [],+ state: 'open',+ title: 'title',+ url: 'https://github.com/octocat/repo/pull/1',+ viewerCanBypass: false,+ viewerCanWrite: true,+ ...overrides,+ },+ status: 'ok',+});++describe('pullRequestDetailRefreshInterval', () => {+ it.each([+ { reviewDecision: 'REVIEW_REQUIRED' as const },+ { reviewDecision: 'CHANGES_REQUESTED' as const },+ { mergeStateStatus: 'BLOCKED' as const },+ { autoMerge: { method: 'squash' as const } },+ ])('keeps polling after checks finish while awaiting %o', (overrides) => {+ const result = detailResult({+ ...overrides,+ checks: [{ name: 'ci', required: true, status: 'success' }],+ });+ expect(pullRequestDetailRefreshInterval(result, true)).toBe(30_000);+ expect(pullRequestDetailRefreshInterval(result, false)).toBe(0);+ for (const state of ['closed', 'merged'] as const) {+ expect(pullRequestDetailRefreshInterval(detailResult({ ...overrides, state }), true)).toBe(0);+ }+ });+ it('returns 0 when not active', () => {+ expect(pullRequestDetailRefreshInterval(detailResult(), false)).toBe(0);+ });++ it('returns 0 when there is no detail', () => {+ expect(pullRequestDetailRefreshInterval({ detail: null, status: 'ok' }, true)).toBe(0);+ });++ it('returns 0 when settled and no pending checks', () => {+ expect(pullRequestDetailRefreshInterval(detailResult(), true)).toBe(0);+ });++ it('polls while mergeable is UNKNOWN', () => {+ expect(pullRequestDetailRefreshInterval(detailResult({ mergeable: 'UNKNOWN' }), true)).toBe(+ 30_000,+ );+ });++ it('polls while a check is pending', () => {+ const result = detailResult({+ checks: [{ name: 'ci', required: true, status: 'pending' }],+ });+ expect(pullRequestDetailRefreshInterval(result, true)).toBe(30_000);+ });+});++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => 'test-workspace',+}));+afterEach(() => vi.restoreAllMocks());++describe('PR bootstrap hooks', () => {+ const setup = () => {+ const cache = new Map();+ const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children);+ const useBootstrap = () => {+ const core = useFetchGitPullRequestDetail('device', '/repo', 42);+ const activity = useFetchGitPullRequestActivity(+ 'device',+ '/repo',+ core.data?.detail?.number,+ false,+ );+ return { core: { ...core }, activity: { ...activity } };+ };+ return { wrapper, useBootstrap };+ };++ it('exposes core before activity, retries activity independently, and dedupes remounts', async () => {+ const detail = detailResult({ number: 42 });+ let resolveCore!: (data: DeviceGitPullRequestDetailResult) => void;+ const coreRead = vi.spyOn(gitService, 'getPullRequestDetail').mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveCore = resolve;+ }),+ );+ const activityRead = vi+ .spyOn(gitService, 'getPullRequestActivity')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValue({ comments: [], commits: [], reviews: [] });+ const { wrapper, useBootstrap } = setup();+ const first = renderHook(useBootstrap, { wrapper });+ await waitFor(() => expect(coreRead).toHaveBeenCalledTimes(1));+ expect(activityRead).not.toHaveBeenCalled();+ await act(async () => resolveCore(detail));+ await waitFor(() => expect(first.result.current.activity.error).toBeDefined());+ expect(first.result.current.core.data?.detail?.title).toBe('title');+ await act(async () => {+ await first.result.current.activity.mutate();+ });+ expect(first.result.current.activity.data?.comments).toEqual([]);+ first.unmount();+ const second = renderHook(useBootstrap, { wrapper });+ expect(second.result.current.core.data?.detail?.title).toBe('title');+ expect(coreRead).toHaveBeenCalledTimes(1);+ expect(activityRead).toHaveBeenCalledTimes(2);+ });++ it('loads new merge context when base changes without a head change', async () => {+ const read = vi.spyOn(gitService, 'getPullRequestMergeContext').mockResolvedValue({+ baseBehindBy: 0,+ requiredChecks: [],+ viewerCanBypass: false,+ viewerCanWrite: true,+ });+ const { wrapper } = setup();+ const { rerender } = renderHook(+ ({ base }) =>+ useFetchGitPullRequestMergeContext('device', '/repo', {+ baseRefName: base,+ headRefOid: 'a'.repeat(40),+ number: 42,+ repo: { owner: 'test', name: 'repo' },+ }),+ { wrapper, initialProps: { base: 'main' } },+ );+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));+ rerender({ base: 'canary' });+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));+ });+});diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex 789ce98494e..95218291426 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -5,6 +5,10 @@ import type {} from '@lobechat/electron-client-ipc';import type {DeviceGitAheadBehind,+ DeviceGitPullRequestActivity,+ DeviceGitPullRequestDetail,+ DeviceGitPullRequestDetailResult,+ DeviceGitPullRequestMergeContext,DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';@@ -17,6 +21,7 @@ export type ReviewMode = 'unstaged' | 'branch';const UNSTAGED_REVIEW_REFRESH_INTERVAL = 10 * 1000;const BRANCH_REVIEW_REFRESH_INTERVAL = 30 * 1000;+const PULL_REQUEST_DETAIL_REFRESH_INTERVAL = 30 * 1000;export interface ReviewPatchesData {baseRef?: string;@@ -198,6 +203,104 @@ export const useFetchGitWorktrees = (deviceId: string | undefined, path?: string{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },);+export const pullRequestDetailRefreshInterval = (+ detail: DeviceGitPullRequestDetailResult | undefined,+ active: boolean,+): number => {+ if (!active || !detail?.detail || detail.detail.state !== 'open') return 0;+ const isPending =+ !!detail.detail.autoMerge ||+ detail.detail.reviewDecision === 'REVIEW_REQUIRED' ||+ detail.detail.reviewDecision === 'CHANGES_REQUESTED' ||+ detail.detail.mergeStateStatus === 'BLOCKED' ||+ detail.detail.mergeable === 'UNKNOWN' ||+ detail.detail.checks.some((c) => c.status === 'pending');+ return isPending ? PULL_REQUEST_DETAIL_REFRESH_INTERVAL : 0;+};++/**+ * Full pull request detail for the Working Sidebar's Pull Request tab. Polls+ * every 30s while checks, reviews, auto-merge, or mergeability haven't resolved+ * yet, and stops once the PR settles into a steady state.+ */+export const useFetchGitPullRequestDetail = (+ deviceId: string | undefined,+ path: string | undefined,+ number: number | undefined,+ { active = true }: { active?: boolean } = {},+) =>+ useClientDataSWR<DeviceGitPullRequestDetailResult | undefined>(+ number !== undefined && isEnabled(deviceId, path)+ ? deviceKeys.gitPullRequestDetail(deviceId ?? 'local', path, number)+ : null,+ () =>+ gitService.getPullRequestDetail({ coreOnly: true, deviceId, number: number!, path: path! }),+ {+ dedupingInterval: 30_000,+ focusThrottleInterval: 60 * 1000,+ refreshInterval: (detail) => pullRequestDetailRefreshInterval(detail, active),+ revalidateOnFocus: true,+ shouldRetryOnError: false,+ },+ );++/** Activity starts once core data can paint; its failure never hides the PR. */+export const useFetchGitPullRequestActivity = (+ deviceId: string | undefined,+ path: string | undefined,+ number: number | undefined,+ active = true,+) =>+ useClientDataSWR<DeviceGitPullRequestActivity>(+ number !== undefined && isEnabled(deviceId, path)+ ? deviceKeys.gitPullRequestActivity(deviceId ?? 'local', path, number)+ : null,+ () => gitService.getPullRequestActivity({ deviceId, number: number!, path: path! }),+ {+ dedupingInterval: 30_000,+ focusThrottleInterval: 60_000,+ refreshInterval: active ? 30_000 : 0,+ shouldRetryOnError: false,+ },+ );++/**+ * Slow merge context (permission, branch protection, base drift), keyed on the+ * PR head so a push refetches it. Runs after the detail so the pane paints first.+ */+export const useFetchGitPullRequestMergeContext = (+ deviceId: string | undefined,+ path: string | undefined,+ detail:+ Pick<DeviceGitPullRequestDetail, 'baseRefName' | 'headRefOid' | 'number' | 'repo'> | undefined,+) =>+ useClientDataSWR<DeviceGitPullRequestMergeContext | null | undefined>(+ detail && isEnabled(deviceId, path)+ ? deviceKeys.gitPullRequestMergeContext(+ deviceId ?? 'local',+ path,+ detail.number,+ detail.headRefOid,+ detail.baseRefName,+ )+ : null,+ () =>+ gitService.getPullRequestMergeContext({+ baseRefName: detail!.baseRefName,+ deviceId,+ headRefOid: detail!.headRefOid,+ number: detail!.number,+ path: path!,+ repo: detail!.repo,+ }),+ {+ dedupingInterval: 30_000,+ focusThrottleInterval: 60 * 1000,+ revalidateOnFocus: true,+ shouldRetryOnError: false,+ },+ );+/*** Lazy-loaded list of remote branches under `refs/remotes/origin/*`.* Disabled until the Review base-ref picker opens.