🤯 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
Fix GitHub PR actions when the session worktree is unavailable (#23299)
Bryancb008285c608
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.tsindex beb66bf0f83..fbcc070e5fe 100644--- a/apps/desktop/src/main/controllers/GitCtr.ts+++ b/apps/desktop/src/main/controllers/GitCtr.ts@@ -107,6 +107,7 @@ export default class GitController extends ControllerModule {action: GitPullRequestAction;number: number;path: string;+ url?: string;}): Promise<GitPullRequestActionResult> {const { runPullRequestAction: runPullRequestActionRpc } = await loadGit();return runPullRequestActionRpc(payload);diff --git a/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.tsindex 6cb63a81d5a..6040fdab2bc 100644--- a/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts@@ -153,6 +153,49 @@ describe('PR mutation workspace boundary', () => {).resolves.toEqual({ success: true });});+ it('routes a ready action by its GitHub URL when the conversation worktree is unregistered', async () => {+ const repository = { path: '/approved/repo', url: 'https://github.com/owner/repo/pull/42' };++ await expect(+ caller.runGitPullRequestAction({+ action: { type: 'ready' },+ deviceId: 'device',+ number: 42,+ path: '/worktrees/unregistered',+ repository,+ }),+ ).resolves.toEqual({ success: true });+ expect(mocks.runGitPullRequestAction).toHaveBeenCalledWith(+ expect.objectContaining({ path: repository.path, url: repository.url }),+ );+ });++ it('rejects a mismatched PR number in an explicit GitHub URL', async () => {+ await expect(+ caller.runGitPullRequestAction({+ action: { type: 'ready' },+ deviceId: 'device',+ number: 42,+ path: '/worktrees/unregistered',+ repository: { path: '/approved/repo', url: 'https://github.com/owner/repo/pull/43' },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ });++ it('keeps local branch deletion scoped to the checkout', async () => {+ await expect(+ caller.runGitPullRequestAction({+ action: { deleteBranch: true, headRefOid: 'a'.repeat(40), method: 'squash', type: 'merge' },+ deviceId: 'device',+ number: 42,+ path: '/worktrees/unregistered',+ repository: { path: '/approved/repo', url: 'https://github.com/owner/repo/pull/42' },+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ });+it('rejects a merge without the displayed head commit', async () => {await expect(caller.runGitPullRequestAction({diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsindex 4181c33432a..4c35272e83f 100644--- a/apps/server/src/routers/lambda/device/git.ts+++ b/apps/server/src/routers/lambda/device/git.ts@@ -8,6 +8,7 @@ import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewarimport { TopicModel } from '@/database/models/topic';import { router } from '@/libs/trpc/lambda';import { deviceGateway } from '@/server/services/deviceGateway';+import { parsePullRequestUrl } from '@/server/services/workRegistration/topicPullRequestLinks';import { WorktreeCleanupService } from '@/server/services/worktreeCleanup';import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';@@ -456,20 +457,29 @@ export const gitRouter = router({deviceId: z.string(),number: z.number().int().positive(),path: z.string(),+ repository: z.object({ path: z.string().min(1), url: z.string().max(2048) }).optional(),}),).mutation(async ({ ctx, input }) => {- await assertWorkspaceRootApproved(- ctx.deviceModel,- input.deviceId,- input.path,- ctx.workspaceId,- );+ const { action, deviceId, number, repository } = input;+ // Deleting the local branch must still run in the selected checkout.+ const target = action.type === 'merge' && action.deleteBranch ? undefined : repository;+ const pullRequest = target && parsePullRequestUrl(target.url);+ if (target && (!pullRequest || pullRequest.number !== number)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Expected the matching GitHub PR URL',+ });+ }++ const path = target?.path ?? input.path;+ await assertWorkspaceRootApproved(ctx.deviceModel, deviceId, path, ctx.workspaceId);return deviceGateway.runGitPullRequestAction({- action: input.action,- deviceId: input.deviceId,- number: input.number,- path: input.path,+ action,+ deviceId,+ number,+ path,+ ...(pullRequest && { url: pullRequest.url }),userId: ctx.userId,workspaceId: ctx.workspaceId,});diff --git a/apps/server/src/services/deviceGateway/gitWrite.ts b/apps/server/src/services/deviceGateway/gitWrite.tsindex 694156c30fe..d6484ee248d 100644--- a/apps/server/src/services/deviceGateway/gitWrite.ts+++ b/apps/server/src/services/deviceGateway/gitWrite.ts@@ -17,6 +17,7 @@ import type {import { OWNED_WORKTREE_RPC_UNSUPPORTED } from '@lobechat/types';import debug from 'debug';+import { gitPullRequestDetail } from './gitRead';import type { DeviceClientGetter } from './types';const log = debug('lobe-server:device-gateway');@@ -464,20 +465,40 @@ export async function runGitPullRequestAction(number: number;path: string;timeout?: number;+ url?: string;userId: string;workspaceId?: string;},): Promise<DeviceGitPullRequestActionResult> {- const { userId, deviceId, path, number, action, timeout = 65_000, workspaceId } = params;+ const { userId, deviceId, path, number, action, url, workspaceId } = params;+ const timeout = params.timeout ?? (url ? 75_000 : 65_000);const client = getClient();if (!client) return { error: 'Device gateway not configured', success: false };try {+ const scope = { deviceId, timeout, userId, workspaceId };+ const legacy = { method: 'runPullRequestAction', params: { action, number, path } };const result = await client.invokeRpc<DeviceGitPullRequestActionResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'runPullRequestAction', params: { action, number, path } },+ scope,+ url ? { method: 'runPullRequestActionByUrl', params: { action, number, path, url } } : legacy,);+ // An explicit unknown method means nothing ran. An older device can still+ // use the approved source checkout once it confirms the same GitHub PR.+ if (+ url &&+ !result.success &&+ result.error?.includes('Unknown device RPC method: runPullRequestActionByUrl')+ ) {+ const confirmed = await gitPullRequestDetail(getClient, { ...params, coreOnly: true });+ if (confirmed?.detail?.url.toLowerCase() !== url.toLowerCase()) {+ return { error: 'The pull request does not match the approved repository', success: false };+ }+ const fallback = await client.invokeRpc<DeviceGitPullRequestActionResult>(scope, legacy);+ if (fallback.success && fallback.data) return fallback.data;+ return { error: fallback.error || 'Pull request action failed', success: false };+ }+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 };diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.tsindex eba1a7de0ec..d6914bcc51e 100644--- a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts@@ -660,6 +660,56 @@ describe('DeviceGateway RPC surface', () => {await expectFailure(c.call(new DeviceGateway()), c.failure, NET_DOWN);});+ describe('PR actions with an explicit URL', () => {+ const url = 'https://github.com/owner/repo/pull/5';+ const run = () =>+ new DeviceGateway().runGitPullRequestAction({+ ...base,+ action: prAction,+ number: 5,+ path: '/approved/repo',+ url,+ });+ const unsupported = {+ error: 'Unknown device RPC method: runPullRequestActionByUrl',+ success: false,+ };++ it('revalidates the URL in the approved repository for older devices', async () => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValueOnce(unsupported);+ mockClient.invokeRpc.mockResolvedValueOnce({ data: { detail: { url } }, success: true });+ mockClient.invokeRpc.mockResolvedValueOnce({ data: { success: true }, success: true });++ await expect(run()).resolves.toEqual({ success: true });+ expect(mockClient.invokeRpc.mock.calls.map(([, payload]) => payload.method)).toEqual([+ 'runPullRequestActionByUrl',+ 'getPullRequestDetail',+ 'runPullRequestAction',+ ]);+ });++ it('does not fall back if the older device resolves a different PR', async () => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValueOnce(unsupported);+ mockClient.invokeRpc.mockResolvedValueOnce({+ data: { detail: { url: 'https://github.com/owner/wrong/pull/5' } },+ success: true,+ });++ await expect(run()).resolves.toMatchObject({ success: false });+ expect(mockClient.invokeRpc).toHaveBeenCalledTimes(2);+ });++ it('does not repeat a mutation after an ambiguous device failure', async () => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValueOnce({ error: 'RPC timed out', success: false });++ await expect(run()).resolves.toEqual({ error: 'RPC timed out', success: false });+ expect(mockClient.invokeRpc).toHaveBeenCalledTimes(1);+ });+ });+describe('listHeterogeneousAgentModels', () => {const call = (type: 'antigravity' | 'codex' = 'codex') =>new DeviceGateway().listHeterogeneousAgentModels({diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 2cf290ba45b..d6976c9840a 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -117,6 +117,7 @@ export const DEVICE_RPC_METHODS = ['getPullRequestActivity','getPullRequestMergeContext','runPullRequestAction',+ 'runPullRequestActionByUrl','getGitWorkingTreeStatus','getGitWorkingTreeFiles','getGitWorkingTreePatches',@@ -413,6 +414,12 @@ export const executeDeviceRpc = async ();}+ case 'runPullRequestActionByUrl': {+ return runPullRequestAction(+ params as { action: GitPullRequestAction; number: number; path: string; url: string },+ );+ }+case 'getGitWorkingTreeStatus': {return getGitWorkingTreeStatus((params as { path: string }).path);}diff --git a/packages/local-file-shell/src/git/__tests__/pullRequest.test.ts b/packages/local-file-shell/src/git/__tests__/pullRequest.test.tsindex 7d4b44f0be4..88d448ad312 100644--- a/packages/local-file-shell/src/git/__tests__/pullRequest.test.ts+++ b/packages/local-file-shell/src/git/__tests__/pullRequest.test.ts@@ -1,3 +1,5 @@+import { tmpdir } from 'node:os';+import { beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -281,6 +283,47 @@ describe('runPullRequestAction head protection', () => {);});+describe('runPullRequestAction by GitHub identity', () => {+ const url = 'https://github.com/owner/repo/pull/42';+ const path = '/registered/source';++ beforeEach(() => {+ childProcessMocks.execFileAsync.mockReset();+ });++ it('marks the confirmed PR ready without running the mutation in a checkout', async () => {+ childProcessMocks.execFileAsync.mockResolvedValueOnce({ stdout: JSON.stringify({ url }) });+ childProcessMocks.execFileAsync.mockResolvedValueOnce({ stdout: '' });++ await expect(+ runPullRequestAction({ action: { type: 'ready' }, number: 42, path, url }),+ ).resolves.toEqual({ success: true });+ expect(childProcessMocks.execFileAsync).toHaveBeenNthCalledWith(+ 1,+ 'gh',+ ['pr', 'view', '42', '--json', 'url'],+ expect.objectContaining({ cwd: path }),+ );+ expect(childProcessMocks.execFileAsync).toHaveBeenNthCalledWith(+ 2,+ 'gh',+ ['pr', 'ready', url],+ expect.objectContaining({ cwd: tmpdir() }),+ );+ });++ it('does not mutate a same-number PR in another repository', async () => {+ childProcessMocks.execFileAsync.mockResolvedValueOnce({+ stdout: JSON.stringify({ url: 'https://github.com/owner/another-repo/pull/42' }),+ });++ await expect(+ runPullRequestAction({ action: { type: 'ready' }, number: 42, path, url }),+ ).resolves.toMatchObject({ success: false });+ expect(childProcessMocks.execFileAsync).toHaveBeenCalledTimes(1);+ });+});+describe('getPullRequestDetail', () => {beforeEach(() => {childProcessMocks.execFileAsync.mockReset();diff --git a/packages/local-file-shell/src/git/pullRequest.ts b/packages/local-file-shell/src/git/pullRequest.tsindex 3d540ee126a..25a527cd319 100644--- a/packages/local-file-shell/src/git/pullRequest.ts+++ b/packages/local-file-shell/src/git/pullRequest.ts@@ -1,4 +1,5 @@import { execFile } from 'node:child_process';+import { tmpdir } from 'node:os';import { promisify } from 'node:util';import { createLogger } from '../logger';@@ -356,8 +357,12 @@ export const getPullRequestDetail = async (payload: {}};-export const pullRequestActionArgs = (number: number, action: GitPullRequestAction): string[][] => {- const n = String(number);+export const pullRequestActionArgs = (+ number: number,+ action: GitPullRequestAction,+ url?: string,+): string[][] => {+ const n = url ?? String(number);if ((action.type === 'merge' || action.type === 'autoMerge') &&!/^[a-f\d]{40}$/i.test(action.headRefOid ?? '')@@ -415,7 +420,17 @@ export const pullRequestActionArgs = (number: number, action: GitPullRequestActi}case 'deleteBranch': {assertBranchName(action.head);- return [['api', '-X', 'DELETE', `repos/{owner}/{repo}/git/refs/heads/${action.head}`]];+ const repo = url ? repoFromPullRequestUrl(url) : { name: '{repo}', owner: '{owner}' };+ const host = url ? ['--hostname', 'github.com'] : [];+ return [+ [+ 'api',+ ...host,+ '-X',+ 'DELETE',+ `repos/${repo.owner}/${repo.name}/git/refs/heads/${action.head}`,+ ],+ ];}case 'changeBase': {assertBranchName(action.base);@@ -428,12 +443,33 @@ export const runPullRequestAction = async (payload: {action: GitPullRequestAction;number: number;path: string;+ url?: string;}): Promise<GitPullRequestActionResult> => {- const { path: dirPath, number, action } = payload;+ const { path: dirPath, number, action, url } = payload;try {- for (const argv of pullRequestActionArgs(number, action)) {- await execFileAsync('gh', argv, { cwd: dirPath, timeout: 60_000 });+ const commands = pullRequestActionArgs(number, action, url);+ if (url) {+ if (action.type === 'merge' && action.deleteBranch)+ throw new Error('Deleting the local branch requires the selected checkout');+ // The cloud has approved dirPath. Resolve the numeric PR there first, so+ // a workspace member cannot use the device's GitHub account on a PR in+ // another repository by supplying its URL.+ const { stdout } = await execFileAsync(+ 'gh',+ ['pr', 'view', String(number), '--json', 'url'],+ {+ cwd: dirPath,+ timeout: 8000,+ },+ );+ const confirmed = JSON.parse(stdout) as { url?: string };+ if (confirmed.url?.toLowerCase() !== url.toLowerCase())+ throw new Error('The pull request does not match the approved repository');+ }++ for (const argv of commands) {+ await execFileAsync('gh', argv, { cwd: url ? tmpdir() : dirPath, timeout: 60_000 });}return { success: true };} catch (error: any) {diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/SidebarTab.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/SidebarTab.tsxindex fe85b0543a1..55e05f4a58c 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/SidebarTab.tsx+++ b/src/features/Conversation/WorkingSidebar/PullRequest/SidebarTab.tsx@@ -16,6 +16,7 @@ interface PullRequestSidebarTabProps {onOpenTab: (tab: string) => void;onRetryConfirm?: () => void;pullRequest: DeviceGitLinkedPullRequest;+ repositoryPath?: string;workingDirectory: string;}@@ -34,7 +35,7 @@ const PullRequestSidebarTab = memo<PullRequestSidebarTabProps>({...rest}active={active}deviceId={deviceId}- key={JSON.stringify([deviceId, workingDirectory, pullRequest.number])}+ key={JSON.stringify([deviceId, workingDirectory, pullRequest.number, pullRequest.url])}number={pullRequest.number}summary={pullRequest}url={pullRequest.url}diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.tsindex fc8474bf447..02a44c0b333 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts@@ -34,6 +34,7 @@ describe('usePullRequestActions', () => {runPullRequestAction.mockReset();pushGitBranch.mockReset();mutate.mockClear();+ revalidateGitStatus.mockReset().mockResolvedValue(undefined);toastError.mockReset();});@@ -132,6 +133,37 @@ describe('usePullRequestActions', () => {expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/other', 'feat/x'))).toBe(false);});+ it('targets the confirmed PR and reports success even if the worktree disappeared', async () => {+ runPullRequestAction.mockResolvedValue({ success: true });+ revalidateGitStatus.mockRejectedValueOnce(new Error('Worktree no longer exists'));+ const url = 'https://github.com/owner/repo/pull/7';+ const { result } = renderHook(() =>+ usePullRequestActions({+ ...params,+ mutateDetail: vi.fn().mockResolvedValue(undefined),+ repositoryPath: '/registered-source',+ url,+ workingDirectory: '/removed-worktree',+ }),+ );++ await act(async () => {+ expect(await result.current.run({ type: 'ready' })).toBe(true);+ });++ expect(result.current.error).toBeUndefined();+ expect(runPullRequestAction).toHaveBeenCalledWith({+ action: { type: 'ready' },+ deviceId: 'dev-1',+ number: 7,+ path: '/removed-worktree',+ repository: { path: '/registered-source', url },+ });+ expect(mutate).toHaveBeenCalledWith(+ deviceKeys.gitPullRequestActivity('dev-1', '/registered-source', 7),+ );+ });+it('keeps dock-action failures as error and retries the same action', async () => {runPullRequestAction.mockResolvedValueOnce({ error: 'base moved', success: false });const { result } = renderHook(() =>diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsxindex 13451b02b58..830d5eb4c16 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx+++ b/src/features/Conversation/WorkingSidebar/PullRequest/index.tsx@@ -45,6 +45,7 @@ interface PullRequestProps {onOpenTab: (tab: string) => void;/** Re-run the branch / linked-PR reads that confirm `number`. */onRetryConfirm?: () => void;+ repositoryPath?: string;summary?: DeviceGitLinkedPullRequest;url?: string;workingDirectory: string;@@ -59,31 +60,37 @@ const PullRequest = memo<PullRequestProps>(number,onOpenTab,onRetryConfirm,+ repositoryPath,summary,url,workingDirectory,}) => {const { t } = useTranslation('chat');const { t: tCommon } = useTranslation('common');+ const readPath = repositoryPath ?? workingDirectory;const {data,error: fetchError,isConfirmed: detailConfirmed,isLoading,mutate,- } = useFetchGitPullRequestDetail(deviceId, workingDirectory, number, { active });+ } = useFetchGitPullRequestDetail(deviceId, readPath, number, { active });+ // A number is only unique within a repository. Do not act on another+ // repository's PR if the source checkout resolves a different remote.+ const matches = !url || data?.detail?.url.toLowerCase() === url.toLowerCase();+ const coreDetail = matches ? data?.detail : undefined;const activity = useFetchGitPullRequestActivity(deviceId,- workingDirectory,- data?.detail?.number,- active && data?.detail?.state === 'open',+ readPath,+ coreDetail?.number,+ active && coreDetail?.state === 'open',);const {data: cachedContext,error: contextError,isConfirmed: contextConfirmed,mutate: mutateContext,- } = useFetchGitPullRequestMergeContext(deviceId, workingDirectory, data?.detail ?? undefined);+ } = useFetchGitPullRequestMergeContext(deviceId, readPath, coreDetail ?? undefined);const { data: aheadBehind } = useFetchGitAheadBehind(deviceId, workingDirectory);// Stale content stays paintable; actions wait for the live reads.const {@@ -98,7 +105,7 @@ const PullRequest = memo<PullRequestProps>(context: cachedContext,contextConfirmed,contextError,- detailConfirmed,+ detailConfirmed: detailConfirmed && matches,detailError: fetchError,});const actions = usePullRequestActions({@@ -107,11 +114,13 @@ const PullRequest = memo<PullRequestProps>(policyLocked,mutateDetail: mutate,number,+ repositoryPath: readPath,+ url: coreDetail?.url,workingDirectory,});const detail = useMemo(() => {- const core = data?.detail ? { ...data.detail, ...activity.data } : undefined;+ const core = coreDetail ? { ...coreDetail, ...activity.data } : undefined;if (!core || !context) return core ?? undefined;const required = new Set(context.requiredChecks);return {@@ -121,7 +130,7 @@ const PullRequest = memo<PullRequestProps>(viewerCanBypass: context.viewerCanBypass,viewerCanWrite: context.viewerCanWrite,};- }, [data?.detail, context, activity.data]);+ }, [coreDetail, context, activity.data]);const externalUrl = detail?.url ?? url;const loadError = (error: unknown, onRetry: () => void) => (<Flexbox {...sectionProps()}>diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.tsindex 6ef3c2bb881..ec32b8e44bc 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts@@ -31,6 +31,8 @@ interface UsePullRequestActionsParams {* refuse policy-driven mutations, but let comments through.*/policyLocked?: boolean;+ repositoryPath?: string;+ url?: string;workingDirectory: string;}@@ -40,6 +42,8 @@ export const usePullRequestActions = ({mutateDetail,policyLocked = false,number,+ repositoryPath,+ url,workingDirectory,}: UsePullRequestActionsParams) => {const [busy, setBusy] = useState<PullRequestBusy>();@@ -72,9 +76,12 @@ export const usePullRequestActions = ({const result = await request();if (!result.success) return fail(result.error || 'unknown error');const cacheDeviceId = deviceId ?? 'local';- await Promise.all([+ const readPath = repositoryPath ?? workingDirectory;+ // The mutation already succeeded. A failed refresh, including a Git+ // status read for a removed worktree, must not make Retry repeat it.+ await Promise.allSettled([mutateDetail(),- mutate(deviceKeys.gitPullRequestActivity(cacheDeviceId, workingDirectory, number)),+ mutate(deviceKeys.gitPullRequestActivity(cacheDeviceId, readPath, number)),mutate((key: unknown) =>Array.isArray(key) &&@@ -87,7 +94,7 @@ export const usePullRequestActions = ({Array.isArray(key) &&key[0] === deviceKeys.gitPullRequestMergeContext.root &&key[1] === cacheDeviceId &&- key[2] === workingDirectory &&+ key[2] === readPath &&key[3] === number,),useGitStatusStore@@ -102,15 +109,21 @@ export const usePullRequestActions = ({setBusy(undefined);}},- [deviceId, mutateDetail, number, workingDirectory],+ [deviceId, mutateDetail, number, repositoryPath, workingDirectory],);const run = useCallback((action: DeviceGitPullRequestAction) =>perform(action.type, () =>- gitService.runPullRequestAction({ action, deviceId, number, path: workingDirectory }),+ gitService.runPullRequestAction({+ action,+ deviceId,+ number,+ path: workingDirectory,+ ...(repositoryPath && url ? { repository: { path: repositoryPath, url } } : {}),+ }),),- [deviceId, number, perform, workingDirectory],+ [deviceId, number, perform, repositoryPath, url, workingDirectory],);const push = useCallback(diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 429964875d6..916da3872b3 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -384,7 +384,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })isGithub,snapshot: snapshotConfig?.git,topicId,- workingDirectory,+ workingDirectory: sourceWorkingDirectory ?? workingDirectory,});const paramsAvailable = !isHetero;// The in-app browser pages are renderer-retained Electron webviews — desktop only.@@ -901,7 +901,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth }){overviewPanel}<TopicPullRequestProbesdeviceId={remoteDeviceId}- path={environmentWorkingDirectory}+ path={sourceWorkingDirectory ?? environmentWorkingDirectory}probes={pullRequestProbes}/><RightPanel@@ -1056,6 +1056,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })className={stylex.props(styles.pane).className}deviceId={remoteDeviceId}pullRequest={pullRequest}+ repositoryPath={sourceWorkingDirectory}workingDirectory={workingDirectory}onOpenTab={openTab}/>diff --git a/src/services/electron/git.ts b/src/services/electron/git.tsindex 6f78abdd7af..b88a35a449a 100644--- a/src/services/electron/git.ts+++ b/src/services/electron/git.ts@@ -85,6 +85,7 @@ class ElectronGitService {action: GitPullRequestAction;number: number;path: string;+ url?: string;}): Promise<GitPullRequestActionResult> {return this.ipc.git.runPullRequestAction(params);}diff --git a/src/services/git.ts b/src/services/git.tsindex 6814826069f..122f90b23e2 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -401,15 +401,31 @@ class GitService {deviceId,number,path,+ repository,}: {action: DeviceGitPullRequestAction;deviceId?: string;number: number;path: string;+ repository?: { path: string; url: string };}): Promise<DeviceGitPullRequestActionResult> {- return deviceId- ? lambdaClient.device.runGitPullRequestAction.mutate({ action, deviceId, number, path })- : electronGitService.runPullRequestAction({ action, number, path });+ if (deviceId) {+ return lambdaClient.device.runGitPullRequestAction.mutate({+ action,+ deviceId,+ number,+ path,+ repository,+ });+ }++ const target = action.type === 'merge' && action.deleteBranch ? undefined : repository;+ return electronGitService.runPullRequestAction({+ action,+ number,+ path: target?.path ?? path,+ url: target?.url,+ });}/** Working-tree dirty-file counts for a working directory. */