diff --git a/src/main/github/client-create-pr.test.ts b/src/main/github/client-create-pr.test.ts index 5fdc811c5..453a6a174 100644 --- a/src/main/github/client-create-pr.test.ts +++ b/src/main/github/client-create-pr.test.ts @@ -25,7 +25,9 @@ vi.mock('./gh-utils', () => ({ repoPath, connectionId: connectionId ?? null })), - ghRepoExecOptions: vi.fn((context: { repoPath: string }) => ({ cwd: context.repoPath })), + ghRepoExecOptions: vi.fn((context: { repoPath: string; connectionId?: string | null }) => + context.connectionId ? {} : { cwd: context.repoPath } + ), gitExecFileAsync: vi.fn(), extractExecError: extractExecErrorMock, parseGitHubOwnerRepo: vi.fn(), @@ -100,6 +102,53 @@ describe('createGitHubPullRequest', () => { expect(releaseMock).toHaveBeenCalledOnce() }) + it('creates SSH-backed pull requests without using the remote path as a local cwd', async () => { + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 45, + url: 'https://github.com/acme/widgets/pull/45' + }) + }) + + await expect( + createGitHubPullRequest( + '/remote/repo-root', + { + provider: 'github', + base: 'main', + head: 'feature/ssh-create-pr', + title: 'SSH Create PR' + }, + 'ssh-1' + ) + ).resolves.toEqual({ + ok: true, + number: 45, + url: 'https://github.com/acme/widgets/pull/45' + }) + + expect(getOwnerRepoMock).toHaveBeenCalledWith('/remote/repo-root', 'ssh-1') + const [args, options] = ghExecFileAsyncMock.mock.calls[0] + expect(args).toEqual( + expect.arrayContaining([ + 'pr', + 'create', + '--repo', + 'acme/widgets', + '--base', + 'main', + '--head', + 'feature/ssh-create-pr' + ]) + ) + expect(options).toMatchObject({ + timeout: 60_000, + idempotent: false + }) + expect(options).not.toHaveProperty('cwd') + }) + it('falls back to parsing the PR URL for older gh output', async () => { getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) ghExecFileAsyncMock.mockResolvedValueOnce({ diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index bcbb5f2e8..14ff735c9 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -6,19 +6,26 @@ const { getIssueMock, listIssuesMock, listWorkItemsMock, - getAuthenticatedViewerMock + getAuthenticatedViewerMock, + mergePRMock, + getAllWebContentsMock } = vi.hoisted(() => ({ handleMock: vi.fn(), getPRForBranchMock: vi.fn(), getIssueMock: vi.fn(), listIssuesMock: vi.fn(), listWorkItemsMock: vi.fn(), - getAuthenticatedViewerMock: vi.fn() + getAuthenticatedViewerMock: vi.fn(), + mergePRMock: vi.fn(), + getAllWebContentsMock: vi.fn() })) vi.mock('electron', () => ({ ipcMain: { handle: handleMock + }, + webContents: { + getAllWebContents: getAllWebContentsMock } })) @@ -27,7 +34,8 @@ vi.mock('../github/client', () => ({ getIssue: getIssueMock, listIssues: listIssuesMock, listWorkItems: listWorkItemsMock, - getAuthenticatedViewer: getAuthenticatedViewerMock + getAuthenticatedViewer: getAuthenticatedViewerMock, + mergePR: mergePRMock })) import { registerGitHubHandlers } from './github' @@ -61,6 +69,9 @@ describe('registerGitHubHandlers', () => { listIssuesMock.mockReset() listWorkItemsMock.mockReset() getAuthenticatedViewerMock.mockReset() + mergePRMock.mockReset() + getAllWebContentsMock.mockReset() + getAllWebContentsMock.mockReturnValue([]) for (const key of Object.keys(handlers)) { delete handlers[key] } @@ -223,6 +234,28 @@ describe('registerGitHubHandlers', () => { ) }) + it('threads SSH connectionId through pull request merge', async () => { + repos[0].connectionId = 'openclaw-2' + mergePRMock.mockResolvedValue({ ok: true }) + + registerGitHubHandlers(store as never, stats as never) + + await handlers['gh:mergePR']( + { sender: { id: 1 } }, + { + repoPath: '/workspace/repo', + prNumber: 42, + method: 'squash', + prRepo: { owner: 'acme', repo: 'orca' } + } + ) + + expect(mergePRMock).toHaveBeenCalledWith('/workspace/repo', 42, 'squash', 'openclaw-2', { + owner: 'acme', + repo: 'orca' + }) + }) + it('forwards the authenticated viewer lookup', async () => { getAuthenticatedViewerMock.mockResolvedValue({ login: 'octocat', email: 'octocat@example.com' }) diff --git a/src/main/ipc/hosted-review.test.ts b/src/main/ipc/hosted-review.test.ts new file mode 100644 index 000000000..8a45a89b9 --- /dev/null +++ b/src/main/ipc/hosted-review.test.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + handleMock, + createHostedReviewMock, + getHostedReviewCreationEligibilityMock, + getHostedReviewForBranchMock, + resolveRegisteredWorktreePathMock, + listRepoWorktreesMock +} = vi.hoisted(() => ({ + handleMock: vi.fn(), + createHostedReviewMock: vi.fn(), + getHostedReviewCreationEligibilityMock: vi.fn(), + getHostedReviewForBranchMock: vi.fn(), + resolveRegisteredWorktreePathMock: vi.fn(), + listRepoWorktreesMock: vi.fn() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: handleMock + } +})) + +vi.mock('../source-control/hosted-review-creation', () => ({ + createHostedReview: createHostedReviewMock, + getHostedReviewCreationEligibility: getHostedReviewCreationEligibilityMock +})) + +vi.mock('../source-control/hosted-review', () => ({ + getHostedReviewForBranch: getHostedReviewForBranchMock +})) + +vi.mock('./filesystem-auth', () => ({ + resolveRegisteredWorktreePath: resolveRegisteredWorktreePathMock +})) + +vi.mock('../repo-worktrees', () => ({ + listRepoWorktrees: listRepoWorktreesMock +})) + +import { registerHostedReviewHandlers } from './hosted-review' + +type HandlerMap = Record unknown> + +describe('registerHostedReviewHandlers', () => { + const handlers: HandlerMap = {} + const repoPath = '/remote/workspace/repo' + const worktreePath = '/remote/workspace/feature-worktree' + const repo = { + id: 'repo-1', + path: repoPath, + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'ssh-1' + } + const store = { + getRepo: vi.fn((repoId: string) => (repoId === repo.id ? repo : null)), + getRepos: vi.fn(() => [repo]) + } + const stats = { + hasCountedPR: vi.fn(() => false), + record: vi.fn() + } + + beforeEach(() => { + handleMock.mockReset() + createHostedReviewMock.mockReset() + getHostedReviewCreationEligibilityMock.mockReset() + getHostedReviewForBranchMock.mockReset() + resolveRegisteredWorktreePathMock.mockReset() + listRepoWorktreesMock.mockReset() + store.getRepo.mockClear() + store.getRepos.mockClear() + stats.hasCountedPR.mockClear() + stats.record.mockClear() + for (const key of Object.keys(handlers)) { + delete handlers[key] + } + handleMock.mockImplementation((channel, handler) => { + handlers[channel] = handler + }) + listRepoWorktreesMock.mockResolvedValue([{ path: worktreePath }]) + }) + + it('passes SSH connectionId through create eligibility instead of blocking the worktree', async () => { + getHostedReviewCreationEligibilityMock.mockResolvedValueOnce({ + provider: 'github', + review: null, + canCreate: true, + blockedReason: null, + nextAction: null, + defaultBaseRef: 'main', + head: 'feature/pr', + title: 'Feature PR', + body: null + }) + + registerHostedReviewHandlers(store as never, stats as never) + + await handlers['hostedReview:getCreationEligibility'](null, { + repoPath, + worktreePath, + branch: 'feature/pr', + base: 'main' + }) + + expect(getHostedReviewCreationEligibilityMock).toHaveBeenCalledWith( + expect.objectContaining({ + repoPath: worktreePath, + connectionId: 'ssh-1', + branch: 'feature/pr', + base: 'main' + }) + ) + expect(resolveRegisteredWorktreePathMock).not.toHaveBeenCalled() + }) + + it('passes SSH connectionId through pull request creation and records successful creates', async () => { + createHostedReviewMock.mockResolvedValueOnce({ + ok: true, + number: 42, + url: 'https://github.com/acme/orca/pull/42' + }) + + registerHostedReviewHandlers(store as never, stats as never) + + await handlers['hostedReview:create'](null, { + repoPath, + worktreePath, + provider: 'github', + base: 'main', + head: 'feature/pr', + title: 'Feature PR', + body: null, + draft: false + }) + + expect(createHostedReviewMock).toHaveBeenCalledWith( + worktreePath, + { + provider: 'github', + base: 'main', + head: 'feature/pr', + title: 'Feature PR', + body: null, + draft: false + }, + 'ssh-1' + ) + expect(resolveRegisteredWorktreePathMock).not.toHaveBeenCalled() + expect(stats.record).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'pr_created', + repoId: 'repo-1', + meta: { prNumber: 42, prUrl: 'https://github.com/acme/orca/pull/42' } + }) + ) + }) +}) diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index 64e143aa8..a26560ce7 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { resolve } from 'path' +import { posix, resolve } from 'path' import type { CreateHostedReviewArgs, HostedReviewCreationEligibilityArgs, @@ -40,6 +40,18 @@ async function resolveHostedReviewWorktreePath( if (!worktreePath) { return repo.path } + if (repo.connectionId) { + const remoteWorktreePath = normalizeRemoteHostedReviewPath(worktreePath) + const repoWorktrees = await listRepoWorktrees(repo) + if ( + !repoWorktrees.some( + (worktree) => normalizeRemoteHostedReviewPath(worktree.path) === remoteWorktreePath + ) + ) { + throw new Error('Access denied: worktree does not belong to repository') + } + return remoteWorktreePath + } const resolvedWorktreePath = await resolveRegisteredWorktreePath(worktreePath, store) const repoWorktrees = await listRepoWorktrees(repo) if (!repoWorktrees.some((worktree) => resolve(worktree.path) === resolvedWorktreePath)) { @@ -48,6 +60,16 @@ async function resolveHostedReviewWorktreePath( return resolvedWorktreePath } +function normalizeRemoteHostedReviewPath(remotePath: string): string { + if (!remotePath || remotePath.includes('\0')) { + throw new Error('Access denied: invalid worktree path') + } + // Why: SSH worktree paths belong to the remote POSIX host. Local path.resolve + // rewrites them on Windows and cannot authorize remote-only paths. + const normalized = posix.normalize(remotePath) + return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized +} + export function registerHostedReviewHandlers(store: Store, stats: StatsCollector): void { ipcMain.handle('hostedReview:forBranch', async (_event, args: HostedReviewForBranchArgs) => { const repo = assertRegisteredRepo(args.repoPath, store, args.repoId) diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index baf3e919d..5abe1b441 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -194,19 +194,17 @@ describe('createHostedReview', () => { it('uses the SSH git provider for remote hosted-review preflight', async () => { const remoteGit = { + getStatus: vi.fn(async () => ({ entries: [], conflictOperation: 'unknown' })), + getUpstreamStatus: vi.fn(async () => ({ + hasUpstream: true, + upstreamName: 'origin/feature', + ahead: 0, + behind: 0 + })), exec: vi.fn(async (args: string[]) => { if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref' && args[2] === 'HEAD') { return { stdout: 'feature\n', stderr: '' } } - if (args[0] === 'status') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'rev-parse' && args[2] === 'HEAD@{u}') { - return { stdout: 'origin/feature\n', stderr: '' } - } - if (args[0] === 'rev-list') { - return { stdout: '0 0\n', stderr: '' } - } if (args[0] === 'log' && args.includes('--pretty=%s')) { return { stdout: 'Feature title\n', stderr: '' } } @@ -239,7 +237,13 @@ describe('createHostedReview', () => { ['rev-parse', '--abbrev-ref', 'HEAD'], '/remote/repo' ) - expect(remoteGit.exec).toHaveBeenCalledWith(['status', '--porcelain'], '/remote/repo') + expect(remoteGit.getStatus).toHaveBeenCalledWith('/remote/repo') + expect(remoteGit.exec).not.toHaveBeenCalledWith(['status', '--porcelain'], '/remote/repo') + expect(remoteGit.getUpstreamStatus).toHaveBeenCalledWith('/remote/repo') + expect(remoteGit.exec).not.toHaveBeenCalledWith( + ['rev-list', '--left-right', '--count', 'HEAD...@{u}'], + '/remote/repo' + ) expect(getUpstreamStatusMock).not.toHaveBeenCalled() expect(ghExecFileAsyncMock).toHaveBeenCalledWith( ['auth', 'status', '--hostname', 'github.com'], diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index bb67ac768..2d0349566 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -159,12 +159,15 @@ async function hasUncommittedChanges( connectionId?: string | null ): Promise { if (connectionId) { - const { stdout } = await runGitForHostedReview( - repoPath, - ['status', '--porcelain'], - connectionId - ) - return stdout.trim().length > 0 + const provider = getSshGitProvider(connectionId) + if (!provider) { + throw new Error( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + } + // Why: the relay intentionally restricts generic git.exec. Use the + // structured status RPC for SSH dirty checks instead of raw `git status`. + return (await provider.getStatus(repoPath)).entries.length > 0 } const { stdout } = await gitExecFileAsync(['status', '--porcelain'], { cwd: repoPath, @@ -182,32 +185,14 @@ async function getHostedReviewUpstreamStatus( if (!connectionId) { return getUpstreamStatus(repoPath) } + const provider = getSshGitProvider(connectionId) + if (!provider) { + throw new Error('Remote connection dropped. Click Reconnect on the SSH target before retrying.') + } try { - const { stdout: upstreamStdout } = await runGitForHostedReview( - repoPath, - ['rev-parse', '--abbrev-ref', 'HEAD@{u}'], - connectionId - ) - const upstreamName = upstreamStdout.trim() - if (!upstreamName) { - return { hasUpstream: false, ahead: 0, behind: 0 } - } - - const { stdout: countsStdout } = await runGitForHostedReview( - repoPath, - ['rev-list', '--left-right', '--count', 'HEAD...@{u}'], - connectionId - ) - const tokens = countsStdout.trim().split(/\s+/) - if (tokens.length !== 2) { - throw new Error(`Unexpected git rev-list output: ${JSON.stringify(countsStdout)}`) - } - const ahead = Number.parseInt(tokens[0]!, 10) - const behind = Number.parseInt(tokens[1]!, 10) - if (!Number.isFinite(ahead) || !Number.isFinite(behind) || ahead < 0 || behind < 0) { - throw new Error(`Unparseable git rev-list counts: ${JSON.stringify(countsStdout)}`) - } - return { hasUpstream: true, upstreamName, ahead, behind } + // Why: SSH exposes upstream divergence through a dedicated relay RPC; + // generic git.exec intentionally does not allow rev-list/status plumbing. + return await provider.getUpstreamStatus(repoPath) } catch (error) { if (isNoUpstreamError(error)) { return { hasUpstream: false, ahead: 0, behind: 0 } diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 25268aefb..3c68df51b 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -218,6 +218,67 @@ describe('hosted review slice', () => { }) }) + it('forwards SSH connectionId when creating pull requests through local IPC', async () => { + mockApi.hostedReview.create.mockResolvedValueOnce({ + ok: true, + number: 12, + url: 'https://github.com/acme/orca/pull/12' + }) + const store = makeStore() + store.setState({ + repos: [{ id: 'repo-1', path: '/repo', connectionId: 'ssh-1' } as AppState['repos'][number]] + }) + + await expect( + store.getState().createHostedReview('/repo', { + provider: 'github', + base: 'main', + head: 'feature/create-pr', + title: 'Create PR', + worktreePath: '/remote/worktree' + }) + ).resolves.toMatchObject({ ok: true, number: 12 }) + + expect(mockApi.hostedReview.create).toHaveBeenCalledWith({ + repoPath: '/repo', + connectionId: 'ssh-1', + provider: 'github', + base: 'main', + head: 'feature/create-pr', + title: 'Create PR', + worktreePath: '/remote/worktree' + }) + }) + + it('forwards SSH connectionId when checking pull request creation eligibility', async () => { + mockApi.hostedReview.getCreationEligibility.mockResolvedValueOnce({ + provider: 'github', + review: null, + canCreate: true, + blockedReason: null, + nextAction: null + }) + const store = makeStore() + store.setState({ + repos: [{ id: 'repo-1', path: '/repo', connectionId: 'ssh-1' } as AppState['repos'][number]] + }) + + await store.getState().getHostedReviewCreationEligibility({ + repoPath: '/repo', + worktreePath: '/remote/worktree', + branch: 'feature/create-pr', + base: 'main' + }) + + expect(mockApi.hostedReview.getCreationEligibility).toHaveBeenCalledWith({ + repoPath: '/repo', + connectionId: 'ssh-1', + worktreePath: '/remote/worktree', + branch: 'feature/create-pr', + base: 'main' + }) + }) + it('uses the selected worktree selector for runtime pull request creation', async () => { runtimeRpc.callRuntimeRpc.mockResolvedValueOnce({ ok: true,