Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(agents): add a Merge button to Magic Chip PR rows and the PR entity (#7347)

Wolf Mermelstein8e817c04e0ed
diff --git a/apps/web/src/features/block-pr/component/MergePullRequestButton.test.tsx b/apps/web/src/features/block-pr/component/MergePullRequestButton.test.tsx
new file mode 100644
index 0000000000..7e9f627dcd
--- /dev/null
+++ b/apps/web/src/features/block-pr/component/MergePullRequestButton.test.tsx
@@ -0,0 +1,157 @@
+/** @vitest-environment jsdom */
+import { queryClient } from '@queries/client';
+import { authServiceClient } from '@service-auth/client';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { confirmDialog } from '@ui';
+import { err, ok } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MergePullRequestButton } from './MergePullRequestButton';
+
+const mocks = vi.hoisted(() => ({
+ success: vi.fn(),
+ failure: vi.fn(),
+}));
+
+vi.mock('@queries/client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return {
+ queryClient: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ };
+});
+vi.mock('@ui', async () => ({
+ Button: (await import('@app/components/ui/components/Button')).Button,
+ cn: (await import('@app/components/ui/utils/classname')).cn,
+ confirmDialog: vi.fn(),
+}));
+vi.mock('@service-auth/client', () => ({
+ authServiceClient: { mergeGithubPullRequest: vi.fn() },
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: mocks.success, failure: mocks.failure },
+}));
+
+const target = {
+ owner: 'macro-inc',
+ repo: 'macro',
+ number: 6369,
+ title: 'Fix reply state',
+};
+
+function renderButton(props: { status: string; onMerged?: () => void }) {
+ return render(() => (
+ <QueryClientProvider client={queryClient}>
+ <MergePullRequestButton target={target} {...props} />
+ </QueryClientProvider>
+ ));
+}
+
+afterEach(() => {
+ cleanup();
+ queryClient.clear();
+ vi.clearAllMocks();
+});
+
+describe('MergePullRequestButton', () => {
+ it('renders only while the pull request is open', () => {
+ const [status, setStatus] = createSignal('open');
+ render(() => (
+ <QueryClientProvider client={queryClient}>
+ <MergePullRequestButton target={target} status={status()} />
+ </QueryClientProvider>
+ ));
+ expect(
+ screen.getByRole('button', { name: 'Merge pull request #6369' })
+ ).toBeTruthy();
+ setStatus('merged');
+ expect(screen.queryByRole('button')).toBeNull();
+ setStatus('closed');
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('confirms, merges as the user, and refreshes the host', async () => {
+ vi.mocked(confirmDialog).mockResolvedValue(true);
+ vi.mocked(authServiceClient.mergeGithubPullRequest).mockResolvedValue(
+ ok({ sha: 'abc123', message: 'Pull Request successfully merged' })
+ );
+ const onMerged = vi.fn();
+ const openHost = vi.fn();
+ render(() => (
+ <QueryClientProvider client={queryClient}>
+ <div onClick={openHost}>
+ <MergePullRequestButton
+ target={target}
+ status="open"
+ onMerged={onMerged}
+ />
+ </div>
+ </QueryClientProvider>
+ ));
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Merge pull request #6369' })
+ );
+
+ await waitFor(() => expect(onMerged).toHaveBeenCalledOnce());
+ expect(confirmDialog).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'Merge pull request?',
+ confirmLabel: 'Merge pull request',
+ }),
+ expect.objectContaining({ owner: expect.any(Object) })
+ );
+ expect(authServiceClient.mergeGithubPullRequest).toHaveBeenCalledWith({
+ owner: 'macro-inc',
+ repo: 'macro',
+ number: 6369,
+ });
+ expect(mocks.success).toHaveBeenCalledWith('Merged macro-inc/macro#6369');
+ expect(openHost).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the confirmation is dismissed', async () => {
+ vi.mocked(confirmDialog).mockResolvedValue(false);
+ renderButton({ status: 'open' });
+
+ fireEvent.click(screen.getByRole('button'));
+
+ await waitFor(() => expect(confirmDialog).toHaveBeenCalledOnce());
+ expect(authServiceClient.mergeGithubPullRequest).not.toHaveBeenCalled();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it("shows GitHub's reason when the merge is declined", async () => {
+ vi.mocked(confirmDialog).mockResolvedValue(true);
+ vi.mocked(authServiceClient.mergeGithubPullRequest).mockResolvedValue(
+ err([
+ {
+ code: 'MERGE_REJECTED',
+ message: 'Pull Request is not mergeable',
+ },
+ ])
+ );
+ const onMerged = vi.fn();
+ renderButton({ status: 'open', onMerged });
+
+ fireEvent.click(screen.getByRole('button'));
+
+ await waitFor(() =>
+ expect(mocks.failure).toHaveBeenCalledWith(
+ 'Pull Request is not mergeable'
+ )
+ );
+ expect(onMerged).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole('button', { name: 'Merge pull request #6369' })
+ ).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx b/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx
new file mode 100644
index 0000000000..d5fd7ccf72
--- /dev/null
+++ b/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx
@@ -0,0 +1,85 @@
+import GitMerge from '@phosphor/git-merge.svg';
+import { Button, type ButtonSize, cn, confirmDialog } from '@ui';
+import { getOwner, Show } from 'solid-js';
+import {
+ createMergePullRequestAction,
+ type MergePullRequestTarget,
+} from '../primitives/create-merge-pull-request-action';
+import { prDisplayName } from '../util/prKey';
+
+/**
+ * Merge an open pull request as the signed-in user. Renders nothing unless
+ * the pull request is open; GitHub's own permissions decide whether the
+ * merge goes through once asked.
+ */
+export function MergePullRequestButton(props: {
+ target: MergePullRequestTarget;
+ status: string | null | undefined;
+ size?: ButtonSize;
+ class?: string;
+ /** Hide the label and show the icon alone, with the label as its name. */
+ iconOnly?: boolean;
+ onMerged?: () => void;
+}) {
+ const owner = getOwner();
+ const action = createMergePullRequestAction({
+ onMerged: props.onMerged,
+ confirm: (target) =>
+ confirmDialog(
+ {
+ title: 'Merge pull request?',
+ get body() {
+ return (
+ <div class="space-y-4 pt-2">
+ <div class="flex items-start gap-3 rounded-lg border border-edge-muted bg-input p-3">
+ <GitMerge
+ aria-hidden="true"
+ class="mt-0.5 size-4 shrink-0 text-ink-muted"
+ />
+ <div class="min-w-0 space-y-1">
+ <Show when={target.title}>
+ <p class="text-sm font-medium text-ink wrap-anywhere">
+ {target.title}
+ </p>
+ </Show>
+ <p class="text-xs text-ink-muted wrap-anywhere">
+ {prDisplayName(target)}
+ </p>
+ </div>
+ </div>
+ <p>
+ This will merge the pull request into its base branch on
+ GitHub.
+ </p>
+ </div>
+ );
+ },
+ confirmLabel: 'Merge pull request',
+ },
+ { owner }
+ ),
+ });
+ const label = () => (action.pending() ? 'Merging…' : 'Merge');
+ return (
+ <Show when={props.status === 'open'}>
+ <Button
+ variant="success"
+ size={props.size ?? 'sm'}
+ noTouchResize
+ class={cn('shrink-0', props.class)}
+ aria-label={`${label()} pull request #${props.target.number}`}
+ disabled={action.pending()}
+ data-merge-pull-request={props.target.number}
+ on:click={(event) => {
+ event.stopPropagation();
+ void action.merge(props.target);
+ }}
+ >
+ <GitMerge aria-hidden="true" class="size-3.5" />
+ <Show when={!props.iconOnly}>
+ <span>{label()}</span>
+ </Show>
+ </Button>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-pr/data/queries.ts b/apps/web/src/features/block-pr/data/queries.ts
index 3fb16bd1d2..06f3b603cc 100644
--- a/apps/web/src/features/block-pr/data/queries.ts
+++ b/apps/web/src/features/block-pr/data/queries.ts
@@ -1,4 +1,5 @@
import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
import { storageServiceClient } from '@service-storage/client';
import type { StoredGithubPullRequest } from '@service-storage/generated/schemas/storedGithubPullRequest';
@@ -20,6 +21,11 @@ export function prForeignEntityQueryKey(id: string): string[] {
return ['github-pr', 'foreign-entity', id];
}
+/** Refetch one PR detail after it was merged. */
+export function invalidatePrForeignEntity(id: string): void {
+ void queryClient.invalidateQueries({ queryKey: prForeignEntityQueryKey(id) });
+}
+
function prForeignEntityDataFromStored(
pullRequest: StoredGithubPullRequest
): PrForeignEntityData {
diff --git a/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts b/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts
new file mode 100644
index 0000000000..bbba2bd19e
--- /dev/null
+++ b/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts
@@ -0,0 +1,62 @@
+import { toast } from '@core/component/Toast/Toast';
+import { ThrownResultError } from '@core/util/result';
+import {
+ type MergeGithubPullRequestInput,
+ useMergeGithubPullRequestMutation,
+} from '@queries/storage/pr-merge';
+import type { Accessor } from 'solid-js';
+import { type PrRef, prDisplayName } from '../util/prKey';
+
+/** The pull request a merge is asked for: its coordinates and a title to show. */
+export type MergePullRequestTarget = PrRef & {
+ title?: string | null;
+};
+
+export type MergePullRequestAction = {
+ /** Ask, then merge. Resolves once the merge settled either way. */
+ merge: (target: MergePullRequestTarget) => Promise<void>;
+ pending: Accessor<boolean>;
+};
+
+function mergeFailureMessage(error: unknown): string {
+ // A declined merge carries GitHub's own reason; anything else is ours.
+ if (error instanceof ThrownResultError && error.errors.length > 0) {
+ return error.message;
+ }
+ return 'Failed to merge pull request';
+}
+
+/**
+ * The merge flow both PR surfaces share: confirm, merge as the signed-in
+ * user, and report the outcome. GitHub decides whether the user may merge
+ * and names what blocks it, so a refusal is shown in GitHub's words.
+ */
+export function createMergePullRequestAction(options: {
+ confirm: (target: MergePullRequestTarget) => Promise<boolean>;
+ onMerged?: (target: MergePullRequestTarget) => void;
+}): MergePullRequestAction {
+ const mutation = useMergeGithubPullRequestMutation();
+
+ const merge = async (target: MergePullRequestTarget) => {
+ if (mutation.isPending) return;
+ const name = prDisplayName(target);
+ const confirmed = await options.confirm(target);
+ if (!confirmed || mutation.isPending) return;
+
+ const input: MergeGithubPullRequestInput = {
+ owner: target.owner,
+ repo: target.repo,
+ number: target.number,
+ };
+ try {
+ await mutation.mutateAsync(input);
+ } catch (error) {
+ toast.failure(mergeFailureMessage(error));
+ return;
+ }
+ toast.success(`Merged ${name}`);
+ options.onMerged?.(target);
+ };
+
+ return { merge, pending: () => mutation.isPending };
+}
diff --git a/apps/web/src/features/block-pr/views/PrDetail.tsx b/apps/web/src/features/block-pr/views/PrDetail.tsx
index 723d4d3485..a8d031cf4b 100644
--- a/apps/web/src/features/block-pr/views/PrDetail.tsx
+++ b/apps/web/src/features/block-pr/views/PrDetail.tsx
@@ -18,6 +18,7 @@ import { githubPullRequestChangesKeys } from '@queries/storage/keys';
import { useQueryClient } from '@tanstack/solid-query';
import { Button, cn, Layer, Scroll } from '@ui';
import { type Accessor, createMemo, Show, Suspense } from 'solid-js';
+import { MergePullRequestButton } from '../component/MergePullRequestButton';
import { PrChangesProvider } from '../component/PrChanges';
import {
PrDescriptionSkeleton,
@@ -34,6 +35,7 @@ import { PrTimeline } from '../component/PrTimeline';
import { PrSidePanelSections } from '../component/sidepanel/PrSidePanelSections';
import { createPrDiscussionSource } from '../data/prDiscussionSource';
import {
+ invalidatePrForeignEntity,
type PrForeignEntityData,
prForeignEntityQueryKey,
usePrForeignEntityQuery,
@@ -188,9 +190,18 @@ export function PrDetailContent(props: PrDetailBodyProps) {
);
}
-export function PrDetailActions() {
+export function PrDetailActions(props: { detail?: PrForeignEntityData }) {
return (
<div class="ml-auto flex shrink-0 items-center gap-2">
+ <Show when={props.detail}>
+ {(detail) => (
+ <MergePullRequestButton
+ target={{ ...detail().prRef, title: detail().pullRequest.name }}
+ status={detail().pullRequest.status}
+ onMerged={() => invalidatePrForeignEntity(detail().id)}
+ />
+ )}
+ </Show>
<ChangesToggle />
<SidePanel.Toggle />
</div>
@@ -228,7 +239,7 @@ export function StandalonePrDetail(props: { foreignEntityId: string }) {
<span class="min-w-0 truncate text-sm font-semibold">
{name()}
</span>
- <PrDetailActions />
+ <PrDetailActions detail={detail.data()} />
</ViewShell.TopBar>
<PrDetailContent
foreignEntityId={props.foreignEntityId}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
index 87dd7f5109..ccb0f080f2 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
@@ -98,7 +98,7 @@ export function ReviewsPrDetail(props: { foreignEntityId: string }) {
<ViewShell.TopBar class="touch:flex">
<SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
<ViewBreadcrumbs.Outlet aria-label="Pull request location" />
- <PrDetailActions />
+ <PrDetailActions detail={detail.data()} />
</ViewShell.TopBar>
<PrDetailContent
foreignEntityId={props.foreignEntityId}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
index 6c69d7f3e9..7101bd596e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.test.tsx
@@ -112,6 +112,9 @@ it('keeps an already mounted chip current through late sync and merge', async ()
).toBeTruthy();
expect(screen.getByLabelText('42 lines added')).toBeTruthy();
expect(screen.getByLabelText('0 lines deleted')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'Merge pull request #6369' })
+ ).toBeTruthy();
await handlePullRequestUpdated({
...entity,
metadata: {
@@ -125,6 +128,9 @@ it('keeps an already mounted chip current through late sync and merge', async ()
await vi.advanceTimersByTimeAsync(1);
expect(screen.getByLabelText('48 lines added')).toBeTruthy();
expect(screen.getByLabelText('2 lines deleted')).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'Merge pull request #6369' })
+ ).toBeNull();
screen.getByRole('button', { name: '#6369 · Fix reply state' }).click();
expect(openWithSplit).toHaveBeenCalledWith(
{ type: 'pr', id: entity.id },
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
index 37dcc42bc4..2ee168d85c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx
@@ -1,3 +1,4 @@
+import { MergePullRequestButton } from '@app/features/block-pr/component/MergePullRequestButton';
import {
parseGithubPrUrl,
prDisplayName,
@@ -27,10 +28,14 @@ export const MagicChipPullRequest: Component<{ url: string }> = (props) => {
? (value as Record<string, unknown>)
: {};
};
+ const text = (key: 'name' | 'status') => {
+ const value = metadata()[key];
+ return typeof value === 'string' ? value : undefined;
+ };
const label = () => {
- const title = metadata().name;
+ const title = text('name');
const parsed = reference();
- return typeof title === 'string' && title
+ return title
? `${parsed ? `#${parsed.number} · ` : ''}${title}`
: parsed
? prDisplayName(parsed)
@@ -104,24 +109,40 @@ export const MagicChipPullRequest: Component<{ url: string }> = (props) => {
}
>
{(pr) => (
- <Button
- variant="ghost"
- size="sm"
- fullWidth
- noTouchResize
- class="h-8 min-w-0 justify-start rounded-lg bg-hover p-2 transition-none not-touch:not-disabled:hover:bg-active not-touch:not-disabled:hover:bg-none not-disabled:active:bg-none"
- aria-label={label()}
- data-magic-chip-pull-request={props.url}
- on:click={(event) => {
- event.stopPropagation();
- layout.openWithSplit(
- { type: 'pr', id: pr().id },
- { preferNewSplit: openInNewSplitForMention(event.shiftKey, true) }
- );
- }}
- >
- {content()}
- </Button>
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ fullWidth
+ noTouchResize
+ class="h-8 min-w-0 flex-1 justify-start rounded-lg bg-hover p-2 transition-none not-touch:not-disabled:hover:bg-active not-touch:not-disabled:hover:bg-none not-disabled:active:bg-none"
+ aria-label={label()}
+ data-magic-chip-pull-request={props.url}
+ on:click={(event) => {
+ event.stopPropagation();
+ layout.openWithSplit(
+ { type: 'pr', id: pr().id },
+ {
+ preferNewSplit: openInNewSplitForMention(
+ event.shiftKey,
+ true
+ ),
+ }
+ );
+ }}
+ >
+ {content()}
+ </Button>
+ <Show when={reference()}>
+ {(prRef) => (
+ <MergePullRequestButton
+ target={{ ...prRef(), title: text('name') }}
+ status={text('status')}
+ class="h-8"
+ />
+ )}
+ </Show>
+ </>
)}
</Show>
);
diff --git a/apps/web/src/lib/queries/storage/pr-merge.ts b/apps/web/src/lib/queries/storage/pr-merge.ts
new file mode 100644
index 0000000000..fffbdea002
--- /dev/null
+++ b/apps/web/src/lib/queries/storage/pr-merge.ts
@@ -0,0 +1,50 @@
+import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import { authServiceClient } from '@service-auth/client';
+import type {
+ MergeGithubPullRequestRequest,
+ MergeGithubPullRequestResponse,
+} from '@service-auth/generated/schemas';
+import { useMutation } from '@tanstack/solid-query';
+import { documentGithubPullRequestsKeys, pullRequestMentionKeys } from './keys';
+
+export type MergeGithubPullRequestInput = MergeGithubPullRequestRequest;
+
+type UseMergeGithubPullRequestMutationOptions = {
+ /** Runs after the shared caches are refreshed, for feature-owned ones. */
+ onSuccess?: (
+ response: MergeGithubPullRequestResponse,
+ input: MergeGithubPullRequestInput
+ ) => void;
+};
+
+/**
+ * Refresh every cached view of pull requests after one was merged: mention
+ * and chip lookups by id and GitHub key, and per-document PR lists. The
+ * merge route patches the stored entity before answering, so a refetch
+ * already sees it merged rather than waiting on GitHub's webhook.
+ */
+export function invalidateMergedPullRequestCaches(): void {
+ void queryClient.invalidateQueries({ queryKey: pullRequestMentionKeys._def });
+ void queryClient.invalidateQueries({
+ queryKey: documentGithubPullRequestsKeys._def,
+ });
+}
+
+/**
+ * Merge a GitHub pull request as the signed-in user, with their own GitHub
+ * grant. GitHub decides whether they may: a refusal rejects with GitHub's
+ * message as the error text, so callers can show it as is.
+ */
+export function useMergeGithubPullRequestMutation(
+ options?: UseMergeGithubPullRequestMutationOptions
+) {
+ return useMutation(() => ({
+ mutationFn: async (input: MergeGithubPullRequestInput) =>
+ await throwOnErr(() => authServiceClient.mergeGithubPullRequest(input)),
+ onSuccess: (response, input) => {
+ invalidateMergedPullRequestCaches();
+ options?.onSuccess?.(response, input);
+ },
+ }));
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index be5c9d748d..8e5d7df087 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -29,6 +29,8 @@ import type {
GmailLinkStatusResponse,
InitGithubLinkResponse,
InitGmailLinkResponse,
+ MergeGithubPullRequestRequest,
+ MergeGithubPullRequestResponse,
PatchUserTutorialRequest,
SendMobileWelcomeEmailResponse,
UserQuota,
@@ -210,6 +212,61 @@ const cursorApiKeyErrorResponseHandler: ErrorResponseHandler<'CURSOR_API_KEY_ERR
};
};
+/**
+ * Errors a merge can end in beyond the shared GitHub ones: the user has no
+ * GitHub account linked, or GitHub declined the merge and said why.
+ */
+export type GithubMergeErrorCode =
+ | GithubReauthenticationErrorCode
+ | 'NO_GITHUB_LINK'
+ | 'MERGE_REJECTED';
+
+/** The body the merge route answers with when the user has not linked GitHub. */
+const NO_GITHUB_LINK_MESSAGE = 'no github link found';
+
+/** The `message` of an error body, or nothing when the body is not that shape. */
+async function readErrorMessage(
+ response: Response
+): Promise<string | undefined> {
+ try {
+ const body: unknown = await response.json();
+ return typeof body === 'object' && body !== null && 'message' in body
+ ? String((body as { message: unknown }).message)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Keeps GitHub's own words on a declined merge. GitHub names the failing
+ * check, the missing review, or the disallowed method; the status alone
+ * ("409") tells the user nothing they can act on.
+ */
+const githubMergeErrorResponseHandler: ErrorResponseHandler<GithubMergeErrorCode> =
+ async function handleGithubMergeErrorResponse(response) {
+ if (response.status === 428) {
+ return {
+ code: 'REAUTHENTICATION_REQUIRED',
+ message: 'GitHub reauthentication required',
+ };
+ }
+ if (![403, 404, 409, 422].includes(response.status)) {
+ return githubErrorResponseHandler(response);
+ }
+ const message = await readErrorMessage(response);
+ if (response.status === 404 && message === NO_GITHUB_LINK_MESSAGE) {
+ return {
+ code: 'NO_GITHUB_LINK',
+ message: 'Connect GitHub in Settings to merge pull requests',
+ };
+ }
+ return {
+ code: 'MERGE_REJECTED',
+ message: message ?? 'GitHub declined to merge the pull request',
+ };
+ };
+
const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =
async function handleGithubErrorResponse(response) {
switch (response.status) {
@@ -445,6 +502,18 @@ export const authServiceClient = {
})
).map((result) => result);
},
+ async mergeGithubPullRequest(args: MergeGithubPullRequestRequest) {
+ return (
+ await fetchWithAuth<MergeGithubPullRequestResponse, GithubMergeErrorCode>(
+ `${authHost}/github_pull_requests/merge`,
+ {
+ method: 'POST',
+ body: JSON.stringify(args),
+ errorResponseHandler: githubMergeErrorResponseHandler,
+ }
+ )
+ ).map((result) => result);
+ },
async patchUserTutorial(args: PatchUserTutorialRequest) {
return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/tutorial`, {
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index b6323421ef..b0f6ceb14a 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -52,6 +52,8 @@ import type {
ListGtmInviteLinksParams,
MacroApiTokenParams,
MacroApiTokenResponse,
+ MergeGithubPullRequestRequest,
+ MergeGithubPullRequestResponse,
PasswordlessCallbackParams,
PasswordlessRequest,
PasswordlessStartedResponse,
@@ -1194,6 +1196,98 @@ export const enrichGithubPullRequests = async (
} as enrichGithubPullRequestsResponse;
};
+/**
+ * @summary Merges a GitHub pull request as the authenticated user, with their own
+GitHub grant. GitHub applies the user's permissions and the repository's
+branch protections; a refusal is returned with GitHub's message.
+ */
+export type mergeGithubPullRequestResponse200 = {
+ data: MergeGithubPullRequestResponse;
+ status: 200;
+};
+
+export type mergeGithubPullRequestResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type mergeGithubPullRequestResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type mergeGithubPullRequestResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type mergeGithubPullRequestResponse409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type mergeGithubPullRequestResponse422 = {
+ data: ErrorResponse;
+ status: 422;
+};
+
+export type mergeGithubPullRequestResponse428 = {
+ data: ErrorResponse;
+ status: 428;
+};
+
+export type mergeGithubPullRequestResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type mergeGithubPullRequestResponseSuccess =
+ mergeGithubPullRequestResponse200 & {
+ headers: Headers;
+ };
+export type mergeGithubPullRequestResponseError = (
+ | mergeGithubPullRequestResponse401
+ | mergeGithubPullRequestResponse403
+ | mergeGithubPullRequestResponse404
+ | mergeGithubPullRequestResponse409
+ | mergeGithubPullRequestResponse422
+ | mergeGithubPullRequestResponse428
+ | mergeGithubPullRequestResponse500
+) & {
+ headers: Headers;
+};
+
+export type mergeGithubPullRequestResponse =
+ | mergeGithubPullRequestResponseSuccess
+ | mergeGithubPullRequestResponseError;
+
+export const getMergeGithubPullRequestUrl = () => {
+ return `/github_pull_requests/merge`;
+};
+
+export const mergeGithubPullRequest = async (
+ mergeGithubPullRequestRequest: MergeGithubPullRequestRequest,
+ options?: RequestInit
+): Promise<mergeGithubPullRequestResponse> => {
+ const res = await fetch(getMergeGithubPullRequestUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(mergeGithubPullRequestRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: mergeGithubPullRequestResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as mergeGithubPullRequestResponse;
+};
+
/**
* @summary Lists invite links, newest first. Macro staff only.
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubMergeMethod.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubMergeMethod.ts
new file mode 100644
index 0000000000..c505844d75
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubMergeMethod.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * How GitHub combines a pull request's commits into its base branch.
+ */
+export type GithubMergeMethod =
+ (typeof GithubMergeMethod)[keyof typeof GithubMergeMethod];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GithubMergeMethod = {
+ merge: 'merge',
+ squash: 'squash',
+ rebase: 'rebase',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index fb54e45c72..513e59edec 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -74,6 +74,7 @@ export * from './getUserInfo';
export * from './getUserInfoOrganizationId';
export * from './getUserLinkExistsParams';
export * from './githubLinkStatusResponse';
+export * from './githubMergeMethod';
export * from './githubPullRequestCheckRun';
export * from './githubPullRequestCheckRunCompletedAt';
export * from './githubPullRequestCheckRunConclusion';
@@ -128,6 +129,10 @@ export * from './linkShare';
export * from './listGtmInviteLinksParams';
export * from './macroApiTokenParams';
export * from './macroApiTokenResponse';
+export * from './mergeGithubPullRequestRequest';
+export * from './mergeGithubPullRequestRequestMergeMethod';
+export * from './mergeGithubPullRequestResponse';
+export * from './mergeGithubPullRequestResponsePullRequest';
export * from './passwordlessCallbackParams';
export * from './passwordlessRequest';
export * from './passwordlessRequestReferralCode';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequest.ts
new file mode 100644
index 0000000000..b68bdb0904
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequest.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MergeGithubPullRequestRequestMergeMethod } from './mergeGithubPullRequestRequestMergeMethod';
+
+/**
+ * A request to merge one pull request on the user's behalf.
+ */
+export interface MergeGithubPullRequestRequest {
+ mergeMethod?: MergeGithubPullRequestRequestMergeMethod;
+ /**
+ * The GitHub pull request number.
+ * @minimum 0
+ */
+ number: number;
+ /** The GitHub repository owner or organization. */
+ owner: string;
+ /** The GitHub repository name. */
+ repo: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequestMergeMethod.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequestMergeMethod.ts
new file mode 100644
index 0000000000..04bf4cda36
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestRequestMergeMethod.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubMergeMethod } from './githubMergeMethod';
+
+export type MergeGithubPullRequestRequestMergeMethod = null | GithubMergeMethod;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponse.ts
new file mode 100644
index 0000000000..a20d2f6677
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponse.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MergeGithubPullRequestResponsePullRequest } from './mergeGithubPullRequestResponsePullRequest';
+
+/**
+ * Response body for a merged pull request.
+ */
+export interface MergeGithubPullRequestResponse {
+ /** GitHub's own summary of the merge. */
+ message: string;
+ pullRequest?: MergeGithubPullRequestResponsePullRequest;
+ /** The merge commit's SHA. */
+ sha: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponsePullRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponsePullRequest.ts
new file mode 100644
index 0000000000..491e51c26b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/mergeGithubPullRequestResponsePullRequest.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EnrichedGithubPullRequest } from './enrichedGithubPullRequest';
+
+export type MergeGithubPullRequestResponsePullRequest =
+ null | EnrichedGithubPullRequest;
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 96272ca8e4..44d18cdf1f 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -842,6 +842,105 @@
}
}
},
+ "/github_pull_requests/merge": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Merges a GitHub pull request as the authenticated user, with their own\nGitHub grant. GitHub applies the user's permissions and the repository's\nbranch protections; a refusal is returned with GitHub's message.",
+ "operationId": "merge_github_pull_request",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeGithubPullRequestRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeGithubPullRequestResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The user cannot push to the repository",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link, or the pull request is not visible to the user",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The pull request is not mergeable as it stands, or its head moved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/gtm-invite/links": {
"get": {
"tags": ["gtm_invite"],
@@ -5450,6 +5549,11 @@
}
}
},
+ "GithubMergeMethod": {
+ "type": "string",
+ "description": "How GitHub combines a pull request's commits into its base branch.",
+ "enum": ["merge", "squash", "rebase"]
+ },
"GithubPullRequestCheckRun": {
"type": "object",
"description": "A check run associated with a GitHub pull request.",
@@ -5939,6 +6043,64 @@
}
}
},
+ "MergeGithubPullRequestRequest": {
+ "type": "object",
+ "description": "A request to merge one pull request on the user's behalf.",
+ "required": ["owner", "repo", "number"],
+ "properties": {
+ "mergeMethod": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GithubMergeMethod",
+ "description": "The merge method to use. Omitted means the first method the\nrepository allows, in the order merge, squash, rebase."
+ }
+ ]
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "MergeGithubPullRequestResponse": {
+ "type": "object",
+ "description": "Response body for a merged pull request.",
+ "required": ["sha", "message"],
+ "properties": {
+ "message": {
+ "type": "string",
+ "description": "GitHub's own summary of the merge."
+ },
+ "pullRequest": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",
+ "description": "The pull request as GitHub reports it after the merge, when the\nrefresh succeeded."
+ }
+ ]
+ },
+ "sha": {
+ "type": "string",
+ "description": "The merge commit's SHA."
+ }
+ }
+ },
"PasswordRequest": {
"type": "object",
"required": ["email", "password"],
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index cfcde54f0b..c074babadc 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -17,9 +17,12 @@ pub(crate) use app_jwt::app_jwt;
pub use github_pull_requests::domain::models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GitRef, GithubKey,
- GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
- GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview,
- GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, latest_reviews,
+ GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun,
+ GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestLabel,
+ GithubPullRequestMerge, GithubPullRequestRef, GithubPullRequestReview,
+ GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser,
+ GithubRepositoryMergeSettings, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ latest_reviews,
};
pub use installation_state::{
InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,
@@ -78,4 +81,13 @@ pub enum GithubError {
/// what they report about other people's accounts.
#[error("no GitHub App installation for this user and repository")]
RepositoryUnavailable,
+ /// GitHub declined to merge the pull request. The message is GitHub's
+ /// own and is written for the person who asked, so it is safe to show.
+ #[error("GitHub declined to merge the pull request: {message}")]
+ PullRequestMergeRejected {
+ /// Why GitHub declined.
+ rejection: GithubMergeRejection,
+ /// GitHub's message for the user.
+ message: String,
+ },
}
diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rs
index 56538fe1cd..f634812c5c 100644
--- a/crates/github/src/domain/ports/link.rs
+++ b/crates/github/src/domain/ports/link.rs
@@ -4,7 +4,9 @@ use std::future::Future;
use crate::domain::models::{
EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubExchangeTokenResponse,
- GithubLink, GithubPullRequestDetails, GithubPullRequestRef, GithubUserInfo,
+ GithubLink, GithubMergeMethod, GithubMergeOutcome, GithubPullRequestDetails,
+ GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
@@ -103,6 +105,27 @@ pub trait GithubOauth: Send + Sync + 'static {
repo: &str,
number: u64,
) -> impl Future<Output = Result<GithubPullRequestDetails, Self::Err>> + Send;
+
+ /// Reads which merge methods a repository allows, as the user sees it.
+ fn get_repository_merge_settings(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ ) -> impl Future<Output = Result<GithubRepositoryMergeSettings, Self::Err>> + Send;
+
+ /// Merges a pull request as the user.
+ ///
+ /// GitHub declining the merge is a [`GithubMergeOutcome::Rejected`]
+ /// value, not an error: the request reached GitHub and was answered.
+ fn merge_pull_request(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ merge_method: GithubMergeMethod,
+ ) -> impl Future<Output = Result<GithubMergeOutcome, Self::Err>> + Send;
}
/// Repository for handling auth related actions.
@@ -181,4 +204,15 @@ pub trait GithubLinkService: Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'static>>,
pull_requests: Vec<GithubPullRequestRef>,
) -> impl Future<Output = Result<Vec<EnrichedGithubPullRequest>, GithubError>> + Send;
+
+ /// Merges a pull request as the user, with their own GitHub grant, so
+ /// GitHub applies the user's permissions and branch protections.
+ ///
+ /// A merge GitHub declines is
+ /// [`GithubError::PullRequestMergeRejected`] with GitHub's message.
+ fn merge_pull_request(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ request: MergeGithubPullRequestRequest,
+ ) -> impl Future<Output = Result<MergeGithubPullRequestResponse, GithubError>> + Send;
}
diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rs
index 2961dfdfc1..3d158fbbf1 100644
--- a/crates/github/src/domain/service/link.rs
+++ b/crates/github/src/domain/service/link.rs
@@ -9,7 +9,9 @@ use macro_user_id::{
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubLink, GithubPullRequestRef,
+ EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubLink, GithubMergeMethod,
+ GithubMergeOutcome, GithubMergeRejection, GithubPullRequestRef,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -104,6 +106,76 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>
Ok(access_token)
}
+ /// The merge method for a request that named none: the first the
+ /// repository allows. When the settings cannot be read, a merge commit is
+ /// attempted and GitHub says so if the repository forbids it; the user
+ /// asked to merge, and a readable refusal beats a failed lookup.
+ async fn resolve_merge_method(
+ &self,
+ access_token: &GithubAccessToken,
+ request: &MergeGithubPullRequestRequest,
+ ) -> Result<GithubMergeMethod, GithubError> {
+ if let Some(method) = request.merge_method {
+ return Ok(method);
+ }
+
+ match self
+ .oauth
+ .get_repository_merge_settings(access_token.as_str(), &request.owner, &request.repo)
+ .await
+ {
+ Ok(settings) => {
+ settings
+ .default_method()
+ .ok_or_else(|| GithubError::PullRequestMergeRejected {
+ rejection: GithubMergeRejection::NotMergeable,
+ message: "This repository does not allow any merge method.".to_string(),
+ })
+ }
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ owner=%request.owner,
+ repo=%request.repo,
+ "failed to read repository merge settings, attempting a merge commit"
+ );
+ Ok(GithubMergeMethod::Merge)
+ }
+ }
+ }
+
+ /// The pull request as GitHub reports it after a merge, written back to
+ /// its foreign entities so the app shows it merged before the webhook
+ /// arrives. Best-effort: the merge already happened.
+ async fn refresh_merged_pull_request(
+ &self,
+ access_token: &GithubAccessToken,
+ reference: GithubPullRequestRef,
+ ) -> Option<EnrichedGithubPullRequest> {
+ let details = self
+ .oauth
+ .get_pull_request_details(
+ access_token.as_str(),
+ &reference.owner,
+ &reference.repo,
+ reference.number,
+ )
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error=?error,
+ owner=%reference.owner,
+ repo=%reference.repo,
+ number=reference.number,
+ "failed to refresh GitHub pull request after merge"
+ );
+ })
+ .ok()?;
+ let pull_request = EnrichedGithubPullRequest::from_details(reference, details);
+ self.refresh_stored_pull_request(&pull_request).await;
+ Some(pull_request)
+ }
+
async fn refresh_stored_pull_request(&self, pull_request: &EnrichedGithubPullRequest) {
if let Err(error) = self
.pull_request_service
@@ -205,6 +277,45 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
Ok(enriched_pull_requests)
}
+ #[tracing::instrument(skip(self), err)]
+ async fn merge_pull_request(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'static>>,
+ request: MergeGithubPullRequestRequest,
+ ) -> Result<MergeGithubPullRequestResponse, GithubError> {
+ let access_token = self.validated_access_token(macro_user_id).await?;
+ let merge_method = self.resolve_merge_method(&access_token, &request).await?;
+
+ let outcome = self
+ .oauth
+ .merge_pull_request(
+ access_token.as_str(),
+ &request.owner,
+ &request.repo,
+ request.number,
+ merge_method,
+ )
+ .await
+ .map_err(|error| GithubError::Internal(error.into()))?;
+
+ let merge = match outcome {
+ GithubMergeOutcome::Merged(merge) => merge,
+ GithubMergeOutcome::Rejected { rejection, message } => {
+ return Err(GithubError::PullRequestMergeRejected { rejection, message });
+ }
+ };
+
+ let pull_request = self
+ .refresh_merged_pull_request(&access_token, request.to_reference())
+ .await;
+
+ Ok(MergeGithubPullRequestResponse {
+ sha: merge.sha,
+ message: merge.message,
+ pull_request,
+ })
+ }
+
#[tracing::instrument(skip(self), err)]
async fn delete_user_link(
&self,
diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rs
index 9ded90c69c..34d3fa7dd6 100644
--- a/crates/github/src/domain/service/link_test.rs
+++ b/crates/github/src/domain/service/link_test.rs
@@ -22,8 +22,10 @@ use macro_user_id::{
use crate::domain::{
models::{
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubAccessToken,
- GithubError, GithubExchangeTokenResponse, GithubLink, GithubPullRequestDetails,
- GithubPullRequestRef, GithubUserInfo,
+ GithubError, GithubExchangeTokenResponse, GithubLink, GithubMergeMethod,
+ GithubMergeOutcome, GithubMergeRejection, GithubPullRequestDetails, GithubPullRequestMerge,
+ GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
+ MergeGithubPullRequestRequest,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -178,6 +180,11 @@ struct StubGithubOauthState {
pull_request_detail_calls: Vec<PullRequestDetailCall>,
pull_request_details: Option<GithubPullRequestDetails>,
pull_request_detail_error: Option<String>,
+ merge_settings: Option<GithubRepositoryMergeSettings>,
+ merge_settings_error: Option<String>,
+ merge_settings_calls: u32,
+ merge_outcome: Option<GithubMergeOutcome>,
+ merge_calls: Vec<MergeCall>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -188,6 +195,15 @@ struct PullRequestDetailCall {
number: u64,
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct MergeCall {
+ access_token: String,
+ owner: String,
+ repo: String,
+ number: u64,
+ merge_method: GithubMergeMethod,
+}
+
impl StubGithubOauth {
fn new(token_is_expired: bool) -> Self {
Self {
@@ -209,6 +225,50 @@ impl StubGithubOauth {
fn fail_pull_request_details(&self, error: &str) {
self.state.lock().unwrap().pull_request_detail_error = Some(error.to_string());
}
+
+ fn with_pull_request_details(self, details: GithubPullRequestDetails) -> Self {
+ self.state.lock().unwrap().pull_request_details = Some(details);
+ self
+ }
+
+ fn with_merge_settings(self, settings: GithubRepositoryMergeSettings) -> Self {
+ self.state.lock().unwrap().merge_settings = Some(settings);
+ self
+ }
+
+ fn fail_merge_settings(self, error: &str) -> Self {
+ self.state.lock().unwrap().merge_settings_error = Some(error.to_string());
+ self
+ }
+
+ fn with_merge_outcome(self, outcome: GithubMergeOutcome) -> Self {
+ self.state.lock().unwrap().merge_outcome = Some(outcome);
+ self
+ }
+
+ fn merge_settings_calls(&self) -> u32 {
+ self.state.lock().unwrap().merge_settings_calls
+ }
+
+ fn merge_calls(&self) -> Vec<MergeCall> {
+ self.state.lock().unwrap().merge_calls.clone()
+ }
+}
+
+fn merged_outcome() -> GithubMergeOutcome {
+ GithubMergeOutcome::Merged(GithubPullRequestMerge {
+ sha: "6dcb09b5".to_string(),
+ message: "Pull Request successfully merged".to_string(),
+ })
+}
+
+fn merge_request(merge_method: Option<GithubMergeMethod>) -> MergeGithubPullRequestRequest {
+ MergeGithubPullRequestRequest {
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ merge_method,
+ }
}
fn default_pull_request_details() -> GithubPullRequestDetails {
@@ -304,6 +364,48 @@ impl GithubOauth for StubGithubOauth {
.clone()
.unwrap_or_else(default_pull_request_details))
}
+
+ async fn get_repository_merge_settings(
+ &self,
+ _access_token: &str,
+ _owner: &str,
+ _repo: &str,
+ ) -> Result<GithubRepositoryMergeSettings, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.merge_settings_calls += 1;
+ if let Some(error) = &state.merge_settings_error {
+ return Err(anyhow::anyhow!(error.clone()));
+ }
+ Ok(state
+ .merge_settings
+ .unwrap_or(GithubRepositoryMergeSettings {
+ allow_merge_commit: true,
+ allow_squash_merge: true,
+ allow_rebase_merge: true,
+ }))
+ }
+
+ async fn merge_pull_request(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ merge_method: GithubMergeMethod,
+ ) -> Result<GithubMergeOutcome, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.merge_calls.push(MergeCall {
+ access_token: access_token.to_string(),
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ number,
+ merge_method,
+ });
+ state
+ .merge_outcome
+ .clone()
+ .ok_or_else(|| anyhow::anyhow!("GitHub unreachable"))
+ }
}
#[derive(Clone)]
@@ -895,6 +997,266 @@ async fn enrich_pull_requests_returns_enriched_response_when_foreign_entity_patc
assert_eq!(foreign_entity_service.patch_calls().len(), 1);
}
+#[tokio::test]
+async fn merge_pull_request_requires_a_valid_grant_before_merging() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(true).with_merge_outcome(merged_outcome());
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("expired-token"),
+ );
+
+ let result = service
+ .merge_pull_request(&user_id, merge_request(None))
+ .await;
+
+ assert!(matches!(result, Err(GithubError::ReauthenticationRequired)));
+ assert!(oauth.merge_calls().is_empty());
+
+ let unlinked = service_with_foreign_entities(
+ StubGithubRepo::unlinked(),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ StubForeignEntityService::default(),
+ );
+ let result = unlinked
+ .merge_pull_request(&user_id, merge_request(None))
+ .await;
+
+ assert!(matches!(result, Err(GithubError::NoLinkFound)));
+ assert!(oauth.merge_calls().is_empty());
+}
+
+#[tokio::test]
+async fn merge_pull_request_uses_the_requested_method_without_reading_settings() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false).with_merge_outcome(merged_outcome());
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let response = service
+ .merge_pull_request(&user_id, merge_request(Some(GithubMergeMethod::Rebase)))
+ .await
+ .unwrap();
+
+ assert_eq!(response.sha, "6dcb09b5");
+ assert_eq!(response.message, "Pull Request successfully merged");
+ assert_eq!(oauth.merge_settings_calls(), 0);
+ assert_eq!(
+ oauth.merge_calls(),
+ vec![MergeCall {
+ access_token: "valid-token".to_string(),
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ merge_method: GithubMergeMethod::Rebase,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn merge_pull_request_picks_the_first_allowed_method_when_none_requested() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false)
+ .with_merge_settings(GithubRepositoryMergeSettings {
+ allow_merge_commit: false,
+ allow_squash_merge: true,
+ allow_rebase_merge: true,
+ })
+ .with_merge_outcome(merged_outcome());
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ service
+ .merge_pull_request(&user_id, merge_request(None))
+ .await
+ .unwrap();
+
+ assert_eq!(oauth.merge_settings_calls(), 1);
+ assert_eq!(
+ oauth.merge_calls()[0].merge_method,
+ GithubMergeMethod::Squash
+ );
+}
+
+#[tokio::test]
+async fn merge_pull_request_rejects_when_the_repository_allows_no_method() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false)
+ .with_merge_settings(GithubRepositoryMergeSettings {
+ allow_merge_commit: false,
+ allow_squash_merge: false,
+ allow_rebase_merge: false,
+ })
+ .with_merge_outcome(merged_outcome());
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let result = service
+ .merge_pull_request(&user_id, merge_request(None))
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(GithubError::PullRequestMergeRejected {
+ rejection: GithubMergeRejection::NotMergeable,
+ ..
+ })
+ ));
+ assert!(oauth.merge_calls().is_empty());
+}
+
+#[tokio::test]
+async fn merge_pull_request_falls_back_to_a_merge_commit_when_settings_are_unreadable() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false)
+ .fail_merge_settings("settings unavailable")
+ .with_merge_outcome(merged_outcome());
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ service
+ .merge_pull_request(&user_id, merge_request(None))
+ .await
+ .unwrap();
+
+ assert_eq!(
+ oauth.merge_calls()[0].merge_method,
+ GithubMergeMethod::Merge
+ );
+}
+
+#[tokio::test]
+async fn merge_pull_request_surfaces_githubs_refusal_with_its_message() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false).with_merge_outcome(GithubMergeOutcome::Rejected {
+ rejection: GithubMergeRejection::NotMergeable,
+ message: "Required status check \"ci\" is expected.".to_string(),
+ });
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![foreign_entity(
+ uuid::Uuid::from_u128(1),
+ "macro/app/pull/7",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({ "status": "open" }),
+ )]);
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+
+ let error = service
+ .merge_pull_request(&user_id, merge_request(Some(GithubMergeMethod::Merge)))
+ .await
+ .unwrap_err();
+
+ match error {
+ GithubError::PullRequestMergeRejected { rejection, message } => {
+ assert_eq!(rejection, GithubMergeRejection::NotMergeable);
+ assert_eq!(message, "Required status check \"ci\" is expected.");
+ }
+ other => panic!("expected a merge rejection, got {other:?}"),
+ }
+ assert!(oauth.pull_request_detail_calls().is_empty());
+ assert!(foreign_entity_service.patch_calls().is_empty());
+}
+
+#[tokio::test]
+async fn merge_pull_request_refreshes_foreign_entities_as_merged() {
+ let user_id = test_user_id();
+ let merged_details = GithubPullRequestDetails {
+ state: "closed".to_string(),
+ merged_at: Some(Utc::now()),
+ ..default_pull_request_details()
+ };
+ let oauth = StubGithubOauth::new(false)
+ .with_merge_outcome(merged_outcome())
+ .with_pull_request_details(merged_details);
+ let foreign_entity_id = uuid::Uuid::from_u128(1);
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![foreign_entity(
+ foreign_entity_id,
+ "macro/app/pull/7",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({ "status": "open", "comments": [{ "id": 1 }] }),
+ )]);
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+
+ let response = service
+ .merge_pull_request(&user_id, merge_request(Some(GithubMergeMethod::Merge)))
+ .await
+ .unwrap();
+
+ let pull_request = response.pull_request.expect("refreshed pull request");
+ assert_eq!(pull_request.github_key, "macro/app/pull/7");
+ assert_eq!(
+ pull_request.status,
+ Some(crate::domain::models::GithubPullRequestStatus::Merged)
+ );
+ assert_eq!(
+ oauth.pull_request_detail_calls(),
+ vec![PullRequestDetailCall {
+ access_token: "valid-token".to_string(),
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ }]
+ );
+ let metadata = foreign_entity_service
+ .foreign_entity_by_id(foreign_entity_id)
+ .unwrap()
+ .metadata;
+ assert_eq!(metadata["status"], "merged");
+ // A refresh carries existing discussion forward rather than dropping it.
+ assert_eq!(metadata["comments"], serde_json::json!([{ "id": 1 }]));
+}
+
+#[tokio::test]
+async fn merge_pull_request_still_reports_the_merge_when_the_refresh_fails() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false).with_merge_outcome(merged_outcome());
+ oauth.fail_pull_request_details("GitHub details unavailable");
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![foreign_entity(
+ uuid::Uuid::from_u128(1),
+ "macro/app/pull/7",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({ "status": "open" }),
+ )]);
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth,
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+
+ let response = service
+ .merge_pull_request(&user_id, merge_request(Some(GithubMergeMethod::Merge)))
+ .await
+ .unwrap();
+
+ assert_eq!(response.sha, "6dcb09b5");
+ assert!(response.pull_request.is_none());
+ assert!(foreign_entity_service.patch_calls().is_empty());
+}
+
#[tokio::test]
async fn link_user_as_sharer_reuses_owner_grant_without_calling_auth() {
let user_id = test_user_id();
diff --git a/crates/github/src/inbound.rs b/crates/github/src/inbound.rs
index d882de9aee..a03bc8e11c 100644
--- a/crates/github/src/inbound.rs
+++ b/crates/github/src/inbound.rs
@@ -9,24 +9,25 @@ pub mod pull_request_index_router;
impl axum::response::IntoResponse for crate::domain::models::GithubError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
- let (status_code, message): (StatusCode, &str) = match self {
+ use std::borrow::Cow;
+ let (status_code, message): (StatusCode, Cow<'static, str>) = match self {
crate::domain::models::GithubError::Internal(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
- "internal server error occurred",
+ "internal server error occurred".into(),
),
crate::domain::models::GithubError::NoLinkFound => {
- (StatusCode::FORBIDDEN, "no account link found")
+ (StatusCode::FORBIDDEN, "no account link found".into())
}
crate::domain::models::GithubError::ReauthenticationRequired => (
StatusCode::PRECONDITION_REQUIRED,
- "ReauthenticationRequired",
+ "ReauthenticationRequired".into(),
),
crate::domain::models::GithubError::NoRefreshTokenProvided => (
StatusCode::UNPROCESSABLE_ENTITY,
- "no refresh token was provided",
+ "no refresh token was provided".into(),
),
crate::domain::models::GithubError::InvalidWebhookSignature => {
- (StatusCode::UNAUTHORIZED, "unauthenticated")
+ (StatusCode::UNAUTHORIZED, "unauthenticated".into())
}
crate::domain::models::GithubError::Forbidden
| crate::domain::models::GithubError::SetupUserNotLinked
@@ -34,23 +35,46 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {
// App is uninstalled or installed somewhere the caller has no
// claim to is a fact about other people's accounts.
| crate::domain::models::GithubError::RepositoryUnavailable => {
- (StatusCode::FORBIDDEN, "forbidden")
+ (StatusCode::FORBIDDEN, "forbidden".into())
}
crate::domain::models::GithubError::InvalidInstallationState
| crate::domain::models::GithubError::InvalidInstallationSetupAction
| crate::domain::models::GithubError::MissingInstallationSetupField(_)
| crate::domain::models::GithubError::InstallationNotOwned => (
StatusCode::BAD_REQUEST,
- "invalid installation setup callback",
+ "invalid installation setup callback".into(),
),
+ // GitHub's message is the one worth showing: it names the failing
+ // check, the missing review, or the disallowed method.
+ crate::domain::models::GithubError::PullRequestMergeRejected {
+ rejection,
+ message,
+ } => (merge_rejection_status(rejection), message.into()),
};
(
status_code,
- axum::Json(model_error_response::ErrorResponse {
- message: message.into(),
- }),
+ axum::Json(model_error_response::ErrorResponse { message }),
)
.into_response()
}
}
+
+/// The status a declined merge is reported with. GitHub's own 405 for "not
+/// mergeable" is misleading on our route (the method is fine), so it becomes
+/// a 409: the pull request's state conflicts with the request.
+#[cfg(feature = "axum")]
+pub fn merge_rejection_status(
+ rejection: crate::domain::models::GithubMergeRejection,
+) -> axum::http::StatusCode {
+ use crate::domain::models::GithubMergeRejection;
+ use axum::http::StatusCode;
+ match rejection {
+ GithubMergeRejection::NotMergeable | GithubMergeRejection::HeadChanged => {
+ StatusCode::CONFLICT
+ }
+ GithubMergeRejection::NotFound => StatusCode::NOT_FOUND,
+ GithubMergeRejection::Forbidden => StatusCode::FORBIDDEN,
+ GithubMergeRejection::Invalid => StatusCode::UNPROCESSABLE_ENTITY,
+ }
+}
diff --git a/crates/github/src/outbound/github_oauth_client.rs b/crates/github/src/outbound/github_oauth_client.rs
index d2310c8787..44d51f9a1c 100644
--- a/crates/github/src/outbound/github_oauth_client.rs
+++ b/crates/github/src/outbound/github_oauth_client.rs
@@ -5,10 +5,21 @@ use std::time::Duration;
use super::pull_request_metadata::fetch_pull_request_metadata;
use crate::domain::{
- models::{GithubExchangeTokenResponse, GithubPullRequestDetails, GithubUserInfo},
+ models::{
+ GithubExchangeTokenResponse, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
+ GithubPullRequestDetails, GithubPullRequestMerge, GithubRepositoryMergeSettings,
+ GithubUserInfo,
+ },
ports::GithubOauth,
};
+#[cfg(test)]
+mod test;
+
+const GITHUB_API_BASE_URL: &str = "https://api.github.com";
+const USER_AGENT: &str = "Macro-Auth-Service";
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
+
/// Github email information from /user/emails endpoint
#[derive(Debug, serde::Deserialize)]
struct GithubEmail {
@@ -25,6 +36,50 @@ struct GithubEmail {
pub struct GithubOauthImpl {
/// The reqwest client
client: reqwest::Client,
+ #[cfg(test)]
+ api_base_url: Option<String>,
+}
+
+/// The `message` GitHub puts in every error body.
+#[derive(serde::Deserialize)]
+struct GithubErrorBody {
+ message: String,
+}
+
+/// Repository settings as GitHub returns them. The `allow_*` fields are only
+/// present for users who can see them; absent means the default, which is
+/// allowed.
+#[derive(serde::Deserialize)]
+struct RepositorySettingsResponse {
+ #[serde(default = "default_true")]
+ allow_merge_commit: bool,
+ #[serde(default = "default_true")]
+ allow_squash_merge: bool,
+ #[serde(default = "default_true")]
+ allow_rebase_merge: bool,
+}
+
+fn default_true() -> bool {
+ true
+}
+
+impl GithubOauthImpl {
+ fn api_base_url(&self) -> &str {
+ #[cfg(test)]
+ if let Some(api_base_url) = &self.api_base_url {
+ return api_base_url;
+ }
+
+ GITHUB_API_BASE_URL
+ }
+
+ #[cfg(test)]
+ fn with_api_base_url(api_base_url: String) -> Self {
+ Self {
+ client: reqwest::Client::default(),
+ api_base_url: Some(api_base_url),
+ }
+ }
}
impl GithubOauth for GithubOauthImpl {
@@ -221,4 +276,109 @@ impl GithubOauth for GithubOauthImpl {
) -> Result<GithubPullRequestDetails, Self::Err> {
fetch_pull_request_metadata(&self.client, access_token, owner, repo, number).await
}
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn get_repository_merge_settings(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ ) -> Result<GithubRepositoryMergeSettings, Self::Err> {
+ let response = self
+ .client
+ .get(format!("{}/repos/{owner}/{repo}", self.api_base_url()))
+ .header("Authorization", format!("Bearer {access_token}"))
+ .header("Accept", "application/vnd.github+json")
+ .header("User-Agent", USER_AGENT)
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .timeout(REQUEST_TIMEOUT)
+ .send()
+ .await?;
+
+ let status = response.status();
+ if !status.is_success() {
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ anyhow::bail!("failed to read repository settings (status {status}): {error_body}");
+ }
+
+ let settings: RepositorySettingsResponse = response.json().await?;
+
+ Ok(GithubRepositoryMergeSettings {
+ allow_merge_commit: settings.allow_merge_commit,
+ allow_squash_merge: settings.allow_squash_merge,
+ allow_rebase_merge: settings.allow_rebase_merge,
+ })
+ }
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn merge_pull_request(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ merge_method: GithubMergeMethod,
+ ) -> Result<GithubMergeOutcome, Self::Err> {
+ #[derive(serde::Serialize)]
+ struct MergeRequest {
+ merge_method: GithubMergeMethod,
+ }
+
+ #[derive(serde::Deserialize)]
+ struct MergeResponse {
+ sha: String,
+ message: String,
+ }
+
+ let response = self
+ .client
+ .put(format!(
+ "{}/repos/{owner}/{repo}/pulls/{number}/merge",
+ self.api_base_url()
+ ))
+ .header("Authorization", format!("Bearer {access_token}"))
+ .header("Accept", "application/vnd.github+json")
+ .header("User-Agent", USER_AGENT)
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .json(&MergeRequest { merge_method })
+ .timeout(REQUEST_TIMEOUT)
+ .send()
+ .await?;
+
+ let status = response.status();
+ if status.is_success() {
+ let merged: MergeResponse = response.json().await?;
+ return Ok(GithubMergeOutcome::Merged(GithubPullRequestMerge {
+ sha: merged.sha,
+ message: merged.message,
+ }));
+ }
+
+ // The statuses GitHub documents for this endpoint, each a decision
+ // about the pull request rather than a failure to reach GitHub.
+ let rejection = match status {
+ reqwest::StatusCode::METHOD_NOT_ALLOWED => GithubMergeRejection::NotMergeable,
+ reqwest::StatusCode::CONFLICT => GithubMergeRejection::HeadChanged,
+ reqwest::StatusCode::NOT_FOUND => GithubMergeRejection::NotFound,
+ reqwest::StatusCode::FORBIDDEN => GithubMergeRejection::Forbidden,
+ reqwest::StatusCode::UNPROCESSABLE_ENTITY => GithubMergeRejection::Invalid,
+ _ => {
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ anyhow::bail!("failed to merge pull request (status {status}): {error_body}");
+ }
+ };
+ let message = response
+ .json::<GithubErrorBody>()
+ .await
+ .map(|body| body.message)
+ .unwrap_or_else(|_| "GitHub declined to merge the pull request.".to_string());
+
+ Ok(GithubMergeOutcome::Rejected { rejection, message })
+ }
}
diff --git a/crates/github/src/outbound/github_oauth_client/test.rs b/crates/github/src/outbound/github_oauth_client/test.rs
new file mode 100644
index 0000000000..37b4f9b6e0
--- /dev/null
+++ b/crates/github/src/outbound/github_oauth_client/test.rs
@@ -0,0 +1,244 @@
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::sync::mpsc::{self, Receiver};
+use std::thread::JoinHandle;
+use std::time::Duration;
+
+use super::*;
+
+struct MockResponse {
+ status: &'static str,
+ body: String,
+}
+
+struct MockServer {
+ base_url: String,
+ requests: Receiver<String>,
+ handle: JoinHandle<()>,
+}
+
+impl MockServer {
+ fn start(response: MockResponse) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let base_url = format!("http://{}", listener.local_addr().unwrap());
+ let (request_sender, requests) = mpsc::channel();
+ let handle = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ let request = read_request(&mut stream);
+ request_sender.send(request).unwrap();
+ write!(
+ stream,
+ "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ response.status,
+ response.body.len(),
+ response.body
+ )
+ .unwrap();
+ });
+
+ Self {
+ base_url,
+ requests,
+ handle,
+ }
+ }
+
+ fn finish(self) -> String {
+ self.handle.join().unwrap();
+ self.requests.recv().unwrap()
+ }
+}
+
+fn read_request(stream: &mut TcpStream) -> String {
+ stream
+ .set_read_timeout(Some(Duration::from_secs(5)))
+ .unwrap();
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 4096];
+
+ loop {
+ let bytes_read = stream.read(&mut buffer).unwrap();
+ if bytes_read == 0 {
+ break;
+ }
+ request.extend_from_slice(&buffer[..bytes_read]);
+
+ let Some(header_end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") else {
+ continue;
+ };
+ let headers = String::from_utf8_lossy(&request[..header_end]);
+ let content_length = headers
+ .lines()
+ .find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length")
+ .then(|| value.trim().parse::<usize>().ok())
+ .flatten()
+ })
+ .unwrap_or(0);
+ if request.len() >= header_end + 4 + content_length {
+ break;
+ }
+ }
+
+ String::from_utf8(request).unwrap()
+}
+
+#[tokio::test]
+async fn merge_pull_request_sends_method_and_reports_merge() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
+ "merged": true,
+ "message": "Pull Request successfully merged"
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .merge_pull_request("token", "macro", "app", 7, GithubMergeMethod::Squash)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ outcome,
+ GithubMergeOutcome::Merged(GithubPullRequestMerge {
+ sha: "6dcb09b5b57875f334f61aebed695e2e4193db5e".to_string(),
+ message: "Pull Request successfully merged".to_string(),
+ })
+ );
+ let request = server.finish();
+ assert!(request.starts_with("PUT /repos/macro/app/pulls/7/merge HTTP/1.1"));
+ assert!(
+ request
+ .to_ascii_lowercase()
+ .contains("authorization: bearer token")
+ );
+ assert!(request.ends_with(r#"{"merge_method":"squash"}"#));
+}
+
+#[tokio::test]
+async fn merge_pull_request_reports_not_mergeable_with_github_message() {
+ let server = MockServer::start(MockResponse {
+ status: "405 Method Not Allowed",
+ body: serde_json::json!({
+ "message": "Required status check \"ci\" is expected.",
+ "documentation_url": "https://docs.github.com"
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .merge_pull_request("token", "macro", "app", 7, GithubMergeMethod::Merge)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ outcome,
+ GithubMergeOutcome::Rejected {
+ rejection: GithubMergeRejection::NotMergeable,
+ message: "Required status check \"ci\" is expected.".to_string(),
+ }
+ );
+ server.finish();
+}
+
+#[tokio::test]
+async fn merge_pull_request_maps_head_change_and_access_statuses() {
+ for (status, expected) in [
+ ("409 Conflict", GithubMergeRejection::HeadChanged),
+ ("404 Not Found", GithubMergeRejection::NotFound),
+ ("403 Forbidden", GithubMergeRejection::Forbidden),
+ ("422 Unprocessable Entity", GithubMergeRejection::Invalid),
+ ] {
+ let server = MockServer::start(MockResponse {
+ status,
+ body: serde_json::json!({ "message": "declined" }).to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .merge_pull_request("token", "macro", "app", 7, GithubMergeMethod::Merge)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ outcome,
+ GithubMergeOutcome::Rejected {
+ rejection: expected,
+ message: "declined".to_string(),
+ },
+ "status {status}"
+ );
+ server.finish();
+ }
+}
+
+#[tokio::test]
+async fn merge_pull_request_treats_unexpected_status_as_error() {
+ let server = MockServer::start(MockResponse {
+ status: "502 Bad Gateway",
+ body: "upstream down".to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let error = client
+ .merge_pull_request("token", "macro", "app", 7, GithubMergeMethod::Merge)
+ .await
+ .unwrap_err();
+
+ assert!(error.to_string().contains("502"));
+ server.finish();
+}
+
+#[tokio::test]
+async fn get_repository_merge_settings_reads_allowed_methods() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "full_name": "macro/app",
+ "allow_merge_commit": false,
+ "allow_squash_merge": true,
+ "allow_rebase_merge": false
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let settings = client
+ .get_repository_merge_settings("token", "macro", "app")
+ .await
+ .unwrap();
+
+ assert_eq!(
+ settings,
+ GithubRepositoryMergeSettings {
+ allow_merge_commit: false,
+ allow_squash_merge: true,
+ allow_rebase_merge: false,
+ }
+ );
+ assert_eq!(settings.default_method(), Some(GithubMergeMethod::Squash));
+ let request = server.finish();
+ assert!(request.starts_with("GET /repos/macro/app HTTP/1.1"));
+}
+
+#[tokio::test]
+async fn get_repository_merge_settings_defaults_missing_fields_to_allowed() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({ "full_name": "macro/app" }).to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let settings = client
+ .get_repository_merge_settings("token", "macro", "app")
+ .await
+ .unwrap();
+
+ assert_eq!(settings.default_method(), Some(GithubMergeMethod::Merge));
+ server.finish();
+}
diff --git a/crates/github_pull_requests/src/domain/models.rs b/crates/github_pull_requests/src/domain/models.rs
index acd010b40b..4655ffbe5a 100644
--- a/crates/github_pull_requests/src/domain/models.rs
+++ b/crates/github_pull_requests/src/domain/models.rs
@@ -25,11 +25,12 @@ pub use index::{PullRequestIndexOutcome, PullRequestIndexRecord, PullRequestInde
pub use key::GithubKey;
pub use pull_request::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
- EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
- GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
- GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview,
- GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestStatus,
- GithubPullRequestUser, latest_reviews,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubMergeMethod,
+ GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun, GithubPullRequestComment,
+ GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestMerge, GithubPullRequestRef,
+ GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState,
+ GithubPullRequestStatus, GithubPullRequestUser, GithubRepositoryMergeSettings,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, latest_reviews,
};
/// A pull request's latest data, for the record stored for one source.
diff --git a/crates/github_pull_requests/src/domain/models/pull_request.rs b/crates/github_pull_requests/src/domain/models/pull_request.rs
index 837a054cf5..c172e87dba 100644
--- a/crates/github_pull_requests/src/domain/models/pull_request.rs
+++ b/crates/github_pull_requests/src/domain/models/pull_request.rs
@@ -666,6 +666,157 @@ fn merge_reviews(
latest_reviews(parse(existing).into_iter().chain(parse(incoming)))
}
+/// How GitHub combines a pull request's commits into its base branch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "lowercase")]
+pub enum GithubMergeMethod {
+ /// A merge commit joining both histories.
+ Merge,
+ /// One squashed commit on the base branch.
+ Squash,
+ /// The pull request's commits replayed onto the base branch.
+ Rebase,
+}
+
+impl GithubMergeMethod {
+ /// The method as GitHub's `merge_method` request value.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Merge => "merge",
+ Self::Squash => "squash",
+ Self::Rebase => "rebase",
+ }
+ }
+}
+
+impl fmt::Display for GithubMergeMethod {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.as_str())
+ }
+}
+
+/// Which merge methods a repository's settings allow.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct GithubRepositoryMergeSettings {
+ /// Merge commits are allowed.
+ pub allow_merge_commit: bool,
+ /// Squash merges are allowed.
+ pub allow_squash_merge: bool,
+ /// Rebase merges are allowed.
+ pub allow_rebase_merge: bool,
+}
+
+impl GithubRepositoryMergeSettings {
+ /// The method a merge should use when the caller expressed no preference:
+ /// the first allowed one in GitHub's own order, or `None` when the
+ /// repository has disabled every method.
+ pub fn default_method(self) -> Option<GithubMergeMethod> {
+ [
+ (self.allow_merge_commit, GithubMergeMethod::Merge),
+ (self.allow_squash_merge, GithubMergeMethod::Squash),
+ (self.allow_rebase_merge, GithubMergeMethod::Rebase),
+ ]
+ .into_iter()
+ .find_map(|(allowed, method)| allowed.then_some(method))
+ }
+}
+
+/// Why GitHub declined to merge a pull request.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GithubMergeRejection {
+ /// The pull request cannot be merged as it stands: conflicts, failing or
+ /// pending required checks, missing reviews, a draft, or a merge method
+ /// the repository does not allow.
+ NotMergeable,
+ /// The head branch moved since the merge was requested.
+ HeadChanged,
+ /// The user's token cannot see the pull request.
+ NotFound,
+ /// The user has no push access to the base repository.
+ Forbidden,
+ /// GitHub rejected the request as invalid.
+ Invalid,
+}
+
+/// A merge GitHub performed.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestMerge {
+ /// The merge commit's SHA.
+ pub sha: String,
+ /// GitHub's own summary of the merge.
+ pub message: String,
+}
+
+/// GitHub's answer to a merge request: performed, or declined with its reason.
+///
+/// A rejection is a fact about the pull request rather than a transport
+/// failure, so the client reports it as a value and the domain decides what
+/// to do with it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum GithubMergeOutcome {
+ /// The pull request was merged.
+ Merged(GithubPullRequestMerge),
+ /// GitHub declined, with the message it gave for the user.
+ Rejected {
+ /// Why GitHub declined.
+ rejection: GithubMergeRejection,
+ /// GitHub's message, written for the person who asked.
+ message: String,
+ },
+}
+
+/// A request to merge one pull request on the user's behalf.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct MergeGithubPullRequestRequest {
+ /// The GitHub repository owner or organization.
+ pub owner: String,
+ /// The GitHub repository name.
+ pub repo: String,
+ /// The GitHub pull request number.
+ pub number: u64,
+ /// The merge method to use. Omitted means the first method the
+ /// repository allows, in the order merge, squash, rebase.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub merge_method: Option<GithubMergeMethod>,
+}
+
+impl MergeGithubPullRequestRequest {
+ /// The reference enrichment uses for this pull request.
+ pub fn to_reference(&self) -> GithubPullRequestRef {
+ GithubPullRequestRef {
+ github_key: format!("{}/{}/pull/{}", self.owner, self.repo, self.number),
+ owner: self.owner.clone(),
+ repo: self.repo.clone(),
+ number: self.number,
+ url: format!(
+ "https://github.com/{}/{}/pull/{}",
+ self.owner, self.repo, self.number
+ ),
+ display_name: format!("{}/{}#{}", self.owner, self.repo, self.number),
+ }
+ }
+}
+
+/// Response body for a merged pull request.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct MergeGithubPullRequestResponse {
+ /// The merge commit's SHA.
+ pub sha: String,
+ /// GitHub's own summary of the merge.
+ pub message: String,
+ /// The pull request as GitHub reports it after the merge, when the
+ /// refresh succeeded.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pull_request: Option<EnrichedGithubPullRequest>,
+}
+
/// Request body for the authenticated pull request enrichment proxy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index a7fb872dd8..ac885484ff 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -844,7 +844,8 @@ When the session has opened a pull request, a compact `#N` status chip
appears in the header (top right) and in the side-panel Details. Click it
to open the PR entity in a split; until GitHub has synced the entity the
chip is a GitHub link instead. The icon and status word follow open /
-merged / closed.
+merged / closed. Merging happens from the PR entity's top bar or from a channel
+Magic Chip's PR row, not from this header chip.
Tool rows show the tool's own name without an MCP server or workspace prefix.
Chat MCP rows retain their service icon.
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 61c4f326e7..b7c4da1f19 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -213,8 +213,15 @@ The lower row shows either a full-width PR preview with available line diff coun
one truncated line of agent output. Failure explanations replace that preview; tool
commands and other secondary details stay inside the session. There are no tooltips.
Click the card or **Open session** to read the full response or answer a question;
-click the PR to open its Macro split (GitHub until its entity has synced). Expanded
-session mentions retain their collapse control. The card never expands in place.
+click the PR to open its Macro split (GitHub until its entity has synced). While the
+synced PR is open, a green **Merge** button sits at the end of the PR row. It asks
+**Merge pull request?** first, showing the title and repository/PR number in the
+shared confirmation dialog (a bottom drawer on phones). **Cancel** returns to the
+chip; **Merge pull request** merges on GitHub with your own linked GitHub account,
+so GitHub's permissions and branch protections apply; a refusal shows
+GitHub's reason as a toast, and success flips the chip to merged without a reload.
+Merged and closed PRs show no Merge button. Expanded session mentions retain their
+collapse control. The card never expands in place.
`@codex` and `@claude` are offered to every user before account setup. The built-in
`@cursor` entry requires the `enable-cursor-agents` rollout flag (local override:
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index d6588997bd..48854777a6 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1430,7 +1430,13 @@ byline.
Macro-linked GitHub pull requests open inside the Reviews shell, with a Reviews
breadcrumb, PR title/status, linked GitHub metadata, discussion timeline, and Details/Checks
-side panel below the top bar. PRs are not tasks and do not appear in the Tasks list.
+side panel below the top bar. An open PR also shows a **Merge** button in the
+top bar beside **Changes**. It opens a confirmation with the repository, PR number,
+and title, then merges on GitHub as the signed-in user through their linked account.
+GitHub's permissions and branch protections decide; a refusal appears as a toast
+with GitHub's reason, and a merge refreshes the PR status in place. Without a linked
+GitHub account the toast points to Settings. Merged and closed PRs have no Merge
+button. PRs are not tasks and do not appear in the Tasks list.
Opening **Changes** slides a full-height pane in from the right beside the PR details,
including beside the PR top bar rather than underneath it. The PR details shrink
alongside the entry slide instead of eagerly jumping narrower. The Changes pane
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index de8f20da7d..e211e7fab5 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index c19b135ea3..70d930e68b 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -269,6 +269,22 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Merges a GitHub pull request as the authenticated user, with their own
+ * GitHub grant. GitHub applies the user's permissions and the repository's
+ * branch protections; a refusal is returned with GitHub's message.
+ */
+ public mergeGithubPullRequest<ThrowOnError extends boolean = false>(options: Options<MergeGithubPullRequestData, ThrowOnError>): RequestResult<MergeGithubPullRequestResponses, MergeGithubPullRequestErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<MergeGithubPullRequestResponses, MergeGithubPullRequestErrors, ThrowOnError>({
+ url: '/github_pull_requests/merge',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Lists invite links, newest first. Macro staff only.
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 31791d6fc3..1c3d7c8baf 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -581,6 +581,11 @@ export type GithubLinkStatusResponse = {
reauthentication_required: boolean;
};
+/**
+ * How GitHub combines a pull request's commits into its base branch.
+ */
+export type GithubMergeMethod = 'merge' | 'squash' | 'rebase';
+
/**
* A check run associated with a GitHub pull request.
*/
@@ -973,6 +978,40 @@ export type MacroApiTokenResponse = {
macro_api_token: string;
};
+/**
+ * A request to merge one pull request on the user's behalf.
+ */
+export type MergeGithubPullRequestRequest = {
+ mergeMethod?: null | GithubMergeMethod;
+ /**
+ * The GitHub pull request number.
+ */
+ number: number;
+ /**
+ * The GitHub repository owner or organization.
+ */
+ owner: string;
+ /**
+ * The GitHub repository name.
+ */
+ repo: string;
+};
+
+/**
+ * Response body for a merged pull request.
+ */
+export type MergeGithubPullRequestResponse = {
+ /**
+ * GitHub's own summary of the merge.
+ */
+ message: string;
+ pullRequest?: null | EnrichedGithubPullRequest;
+ /**
+ * The merge commit's SHA.
+ */
+ sha: string;
+};
+
export type PasswordRequest = {
/**
* The email to login with
@@ -2052,6 +2091,40 @@ export type EnrichGithubPullRequestsResponses = {
export type EnrichGithubPullRequestsResponse2 = EnrichGithubPullRequestsResponses[keyof EnrichGithubPullRequestsResponses];
+export type MergeGithubPullRequestData = {
+ body: MergeGithubPullRequestRequest;
+ path?: never;
+ query?: never;
+ url: '/github_pull_requests/merge';
+};
+
+export type MergeGithubPullRequestErrors = {
+ 401: ErrorResponse;
+ /**
+ * The user cannot push to the repository
+ */
+ 403: ErrorResponse;
+ /**
+ * No GitHub link, or the pull request is not visible to the user
+ */
+ 404: ErrorResponse;
+ /**
+ * The pull request is not mergeable as it stands, or its head moved
+ */
+ 409: ErrorResponse;
+ 422: ErrorResponse;
+ 428: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type MergeGithubPullRequestError = MergeGithubPullRequestErrors[keyof MergeGithubPullRequestErrors];
+
+export type MergeGithubPullRequestResponses = {
+ 200: MergeGithubPullRequestResponse;
+};
+
+export type MergeGithubPullRequestResponse2 = MergeGithubPullRequestResponses[keyof MergeGithubPullRequestResponses];
+
export type ListGtmInviteLinksData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 96272ca8e4..44d18cdf1f 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -842,6 +842,105 @@
}
}
},
+ "/github_pull_requests/merge": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Merges a GitHub pull request as the authenticated user, with their own\nGitHub grant. GitHub applies the user's permissions and the repository's\nbranch protections; a refusal is returned with GitHub's message.",
+ "operationId": "merge_github_pull_request",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeGithubPullRequestRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeGithubPullRequestResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The user cannot push to the repository",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link, or the pull request is not visible to the user",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The pull request is not mergeable as it stands, or its head moved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/gtm-invite/links": {
"get": {
"tags": ["gtm_invite"],
@@ -5450,6 +5549,11 @@
}
}
},
+ "GithubMergeMethod": {
+ "type": "string",
+ "description": "How GitHub combines a pull request's commits into its base branch.",
+ "enum": ["merge", "squash", "rebase"]
+ },
"GithubPullRequestCheckRun": {
"type": "object",
"description": "A check run associated with a GitHub pull request.",
@@ -5939,6 +6043,64 @@
}
}
},
+ "MergeGithubPullRequestRequest": {
+ "type": "object",
+ "description": "A request to merge one pull request on the user's behalf.",
+ "required": ["owner", "repo", "number"],
+ "properties": {
+ "mergeMethod": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GithubMergeMethod",
+ "description": "The merge method to use. Omitted means the first method the\nrepository allows, in the order merge, squash, rebase."
+ }
+ ]
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "MergeGithubPullRequestResponse": {
+ "type": "object",
+ "description": "Response body for a merged pull request.",
+ "required": ["sha", "message"],
+ "properties": {
+ "message": {
+ "type": "string",
+ "description": "GitHub's own summary of the merge."
+ },
+ "pullRequest": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",
+ "description": "The pull request as GitHub reports it after the merge, when the\nrefresh succeeded."
+ }
+ ]
+ },
+ "sha": {
+ "type": "string",
+ "description": "The merge commit's SHA."
+ }
+ }
+ },
"PasswordRequest": {
"type": "object",
"required": ["email", "password"],
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 8c4ab0e14e..c31e40c371 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -89,6 +89,7 @@ export const authExcluded = [
'listCursorModels',
'listGtmInviteLinks',
'logout',
+ 'mergeGithubPullRequest',
'oauth2Callback',
'oauthRedirect',
'passwordLogin',
diff --git a/services/authentication_service/src/api/github_pull_requests.rs b/services/authentication_service/src/api/github_pull_requests.rs
index 1f05a2e41f..cb595b268e 100644
--- a/services/authentication_service/src/api/github_pull_requests.rs
+++ b/services/authentication_service/src/api/github_pull_requests.rs
@@ -6,7 +6,10 @@ use axum::{
routing::post,
};
use github::domain::{
- models::{EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, GithubError},
+ models::{
+ EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, GithubError,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ },
ports::GithubLinkService,
};
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
@@ -46,8 +49,50 @@ impl IntoResponse for EnrichGithubPullRequestsProxyError {
}
}
+#[derive(thiserror::Error, Debug)]
+pub enum MergeGithubPullRequestError {
+ #[error(transparent)]
+ Github(#[from] GithubError),
+}
+
+impl IntoResponse for MergeGithubPullRequestError {
+ fn into_response(self) -> Response {
+ let (status_code, message) = match self {
+ Self::Github(GithubError::NoLinkFound) => {
+ (StatusCode::NOT_FOUND, "no github link found".to_string())
+ }
+ Self::Github(GithubError::ReauthenticationRequired) => (
+ StatusCode::PRECONDITION_REQUIRED,
+ "reauthentication required".to_string(),
+ ),
+ // GitHub's own message names what blocks the merge; the status
+ // says which kind of refusal it is.
+ Self::Github(GithubError::PullRequestMergeRejected { rejection, message }) => {
+ (github::inbound::merge_rejection_status(rejection), message)
+ }
+ Self::Github(error) => {
+ tracing::error!(error=?error, "failed to merge GitHub pull request");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "internal error".to_string(),
+ )
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
pub fn router() -> Router<ApiContext> {
- Router::new().route("/enrich", post(handler))
+ Router::new()
+ .route("/enrich", post(handler))
+ .route("/merge", post(merge_handler))
}
/// Enriches GitHub pull request references with live GitHub data for the authenticated user.
@@ -82,3 +127,38 @@ pub async fn handler(
Ok(Json(EnrichGithubPullRequestsResponse { pull_requests }))
}
+
+/// Merges a GitHub pull request as the authenticated user, with their own
+/// GitHub grant. GitHub applies the user's permissions and the repository's
+/// branch protections; a refusal is returned with GitHub's message.
+#[utoipa::path(
+ post,
+ path = "/github_pull_requests/merge",
+ operation_id = "merge_github_pull_request",
+ request_body = MergeGithubPullRequestRequest,
+ responses(
+ (status = 200, body = MergeGithubPullRequestResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, description = "The user cannot push to the repository", body = ErrorResponse),
+ (status = 404, description = "No GitHub link, or the pull request is not visible to the user", body = ErrorResponse),
+ (status = 409, description = "The pull request is not mergeable as it stands, or its head moved", body = ErrorResponse),
+ (status = 422, body = ErrorResponse),
+ (status = 428, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.authorization.user.macro_user_id), err)]
+pub async fn merge_handler(
+ State(ctx): State<ApiContext>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ extract::Json(request): extract::Json<MergeGithubPullRequestRequest>,
+) -> Result<Json<MergeGithubPullRequestResponse>, MergeGithubPullRequestError> {
+ tracing::info!("merge_github_pull_request");
+
+ let response = ctx
+ .github_link_service
+ .merge_pull_request(&authorization.authorization.user.macro_user_id, request)
+ .await?;
+
+ Ok(Json(response))
+}
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index c7ba4042f1..f70e469af7 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -1,7 +1,8 @@
use github::domain::models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
- EnrichedGithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment,
- GithubPullRequestRef, GithubPullRequestStatus,
+ EnrichedGithubPullRequest, GithubMergeMethod, GithubPullRequestCheckRun,
+ GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
};
use gtm_invite::inbound::axum_router::dto::{
CreateGtmInviteLinkRequest, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus,
@@ -108,6 +109,7 @@ use model::user::{
/// /github_pull_requests
github_pull_requests::handler,
+ github_pull_requests::merge_handler,
/// /oauth
oauth::oauth_redirect::handler,
@@ -258,6 +260,9 @@ use model::user::{
GithubPullRequestComment,
GithubPullRequestRef,
GithubPullRequestStatus,
+ GithubMergeMethod,
+ MergeGithubPullRequestRequest,
+ MergeGithubPullRequestResponse,
UserQuota,
UserOrganizationResponse,
@@ -328,6 +333,44 @@ mod tests {
assert!(operation["responses"].get("428").is_some());
}
+ #[test]
+ fn github_pull_requests_openapi_includes_merge_path() {
+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();
+ let operation = &openapi["paths"]["/github_pull_requests/merge"]["post"];
+
+ assert_eq!(operation["operationId"], "merge_github_pull_request");
+ assert_eq!(
+ operation["requestBody"]["content"]["application/json"]["schema"]["$ref"].as_str(),
+ Some("#/components/schemas/MergeGithubPullRequestRequest")
+ );
+ assert_eq!(
+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),
+ Some("#/components/schemas/MergeGithubPullRequestResponse")
+ );
+ for status in ["403", "404", "409", "422", "428"] {
+ assert!(
+ operation["responses"].get(status).is_some(),
+ "missing {status} response"
+ );
+ }
+
+ let schemas = &openapi["components"]["schemas"];
+ let request_properties = &schemas["MergeGithubPullRequestRequest"]["properties"];
+ for property in ["owner", "repo", "number", "mergeMethod"] {
+ assert!(
+ request_properties.get(property).is_some(),
+ "missing request property {property}"
+ );
+ }
+ assert_eq!(
+ schemas["GithubMergeMethod"]["enum"],
+ serde_json::json!(["merge", "squash", "rebase"])
+ );
+ let response_properties = &schemas["MergeGithubPullRequestResponse"]["properties"];
+ assert!(response_properties.get("sha").is_some());
+ assert!(response_properties.get("pullRequest").is_some());
+ }
+
#[test]
fn github_link_status_openapi_includes_path_and_schema() {
let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();