Surface GitHub auto-merge actions (#1001)

* Surface GitHub auto-merge actions

* Namespace GitHub auto-merge RPC

* Update workspace git refresh test expectation

* Avoid redundant GitHub refresh queue
This commit is contained in:
Mohamed Boudra
2026-05-14 17:48:05 +08:00
committed by GitHub
parent 44292b2b69
commit eb7fa02ac8
27 changed files with 3029 additions and 105 deletions
@@ -1586,6 +1586,118 @@ test("requests checkout merge from base via RPC", async () => {
});
});
test("requests GitHub auto-merge enable via namespaced RPC", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen();
await connectPromise;
const promise = client.checkoutGithubSetAutoMerge(
"/tmp/project",
{ enabled: true, method: "squash" },
"req-enable-auto-merge",
);
expect(mock.sent).toHaveLength(1);
const request = parseSentFrame(mock.sent[0]);
expect(request.type).toBe("checkout.github.set_auto_merge.request");
expect(request.cwd).toBe("/tmp/project");
expect(request.enabled).toBe(true);
expect(request.mergeMethod).toBe("squash");
expect(request.requestId).toBe("req-enable-auto-merge");
mock.triggerMessage(
JSON.stringify({
type: "session",
message: {
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/project",
enabled: true,
requestId: "req-enable-auto-merge",
success: true,
error: null,
},
},
}),
);
await expect(promise).resolves.toEqual({
cwd: "/tmp/project",
enabled: true,
requestId: "req-enable-auto-merge",
success: true,
error: null,
});
});
test("requests GitHub auto-merge disable via namespaced RPC", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen();
await connectPromise;
const promise = client.checkoutGithubSetAutoMerge(
"/tmp/project",
{ enabled: false },
"req-disable-auto-merge",
);
expect(mock.sent).toHaveLength(1);
const request = parseSentFrame(mock.sent[0]);
expect(request.type).toBe("checkout.github.set_auto_merge.request");
expect(request.cwd).toBe("/tmp/project");
expect(request.enabled).toBe(false);
expect(request.mergeMethod).toBeUndefined();
expect(request.requestId).toBe("req-disable-auto-merge");
mock.triggerMessage(
JSON.stringify({
type: "session",
message: {
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/project",
enabled: false,
requestId: "req-disable-auto-merge",
success: true,
error: null,
},
},
}),
);
await expect(promise).resolves.toEqual({
cwd: "/tmp/project",
enabled: false,
requestId: "req-disable-auto-merge",
success: true,
error: null,
});
});
test("requests checkout pull via RPC", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
@@ -32,6 +32,7 @@ import type {
CheckoutPrCreateResponse,
CheckoutPrMergeResponse,
CheckoutPrMergeMethod,
CheckoutGithubSetAutoMergeResponse,
CheckoutPrStatusResponse,
PullRequestTimelineResponse,
CheckoutSwitchBranchResponse,
@@ -274,6 +275,7 @@ type CheckoutPullPayload = CheckoutPullResponse["payload"];
type CheckoutPushPayload = CheckoutPushResponse["payload"];
type CheckoutPrCreatePayload = CheckoutPrCreateResponse["payload"];
type CheckoutPrMergePayload = CheckoutPrMergeResponse["payload"];
type CheckoutGithubSetAutoMergePayload = CheckoutGithubSetAutoMergeResponse["payload"];
type CheckoutPrStatusPayload = CheckoutPrStatusResponse["payload"];
type PullRequestTimelinePayload = PullRequestTimelineResponse["payload"];
type CheckoutSwitchBranchPayload = CheckoutSwitchBranchResponse["payload"];
@@ -1425,6 +1427,25 @@ export class DaemonClient {
});
}
private sendNamespacedCorrelatedSessionRequest<
TResponseType extends CorrelatedResponseType,
TResult = CorrelatedResponsePayload<TResponseType>,
>(params: {
requestId?: string;
message: { type: Extract<SessionInboundMessage["type"], `${string}.request`> } & Record<
string,
unknown
>;
timeout: number;
selectPayload?: (payload: CorrelatedResponsePayload<TResponseType>) => TResult | null;
}): Promise<TResult> {
const responseType = params.message.type.replace(/\.request$/, ".response") as TResponseType;
return this.sendCorrelatedSessionRequest({
...params,
responseType,
});
}
private sendSessionMessageStrict(message: SessionInboundMessage): void {
if (!this.transport || this.connectionState.status !== "connected") {
throw new Error("Transport not connected");
@@ -2817,6 +2838,23 @@ export class DaemonClient {
});
}
async checkoutGithubSetAutoMerge(
cwd: string,
input: { enabled: true; method: CheckoutPrMergeMethod } | { enabled: false },
requestId?: string,
): Promise<CheckoutGithubSetAutoMergePayload> {
return this.sendNamespacedCorrelatedSessionRequest<"checkout.github.set_auto_merge.response">({
requestId,
message: {
type: "checkout.github.set_auto_merge.request",
cwd,
enabled: input.enabled,
...(input.enabled ? { mergeMethod: input.method } : {}),
},
timeout: 60000,
});
}
async checkoutPrStatus(cwd: string, requestId?: string): Promise<CheckoutPrStatusPayload> {
return this.sendCorrelatedSessionRequest({
requestId,
@@ -35,4 +35,63 @@ describe("checkout status projection", () => {
expect(payload).toHaveProperty("mergeable", "MERGEABLE");
expect(CheckoutPrStatusSchema.parse(payload)).toEqual(payload);
});
test("projects PR 993 GitHub merge facts without changing top-level status fields", () => {
const payload = normalizeCheckoutPrStatusPayload({
number: 993,
repoOwner: "getpaseo",
repoName: "paseo",
url: "https://github.com/getpaseo/paseo/pull/993",
title: "Auto-merge UX",
state: "open",
baseRefName: "main",
headRefName: "github-pr-auto-merge-ux",
isMerged: false,
isDraft: false,
mergeable: "MERGEABLE",
checks: [
{
name: "server tests",
status: "pending",
url: "https://github.com/getpaseo/paseo/actions/runs/993",
workflow: "CI",
},
],
checksStatus: "pending",
reviewDecision: "approved",
github: {
mergeStateStatus: "BLOCKED",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: false,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
});
expect(payload).toMatchObject({
number: 993,
mergeable: "MERGEABLE",
checksStatus: "pending",
github: {
mergeStateStatus: "BLOCKED",
viewerCanEnableAutoMerge: true,
repository: {
autoMergeAllowed: true,
squashMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
},
});
expect(CheckoutPrStatusSchema.parse(payload)).toEqual(payload);
});
});
@@ -115,7 +115,7 @@ export function normalizeCheckoutPrStatusPayload(
if (!status) {
return null;
}
return {
const payload: CheckoutPrStatusPayloadStatus = {
number: status.number,
url: status.url,
title: status.title,
@@ -131,4 +131,8 @@ export function normalizeCheckoutPrStatusPayload(
checksStatus: status.checksStatus,
reviewDecision: status.reviewDecision,
};
if (status.github) {
payload.github = status.github;
}
return payload;
}
+543 -1
View File
@@ -46,6 +46,7 @@ import {
createProviderSnapshotManagerStub,
} from "./test-utils/session-stubs.js";
import { isPlatform } from "../test-utils/platform.js";
import type { GitHubPullRequestStatusFacts } from "../services/github-service.js";
interface SessionHandlerInternals {
startVoiceTurnController(): Promise<void>;
@@ -64,6 +65,7 @@ interface SessionHandlerInternals {
handleCheckoutCommitRequest(params: unknown): Promise<unknown>;
handleCheckoutPrCreateRequest(params: unknown): Promise<unknown>;
handleCheckoutPrMergeRequest(params: unknown): Promise<unknown>;
handleCheckoutGithubSetAutoMergeRequest(params: unknown): Promise<unknown>;
handleCheckoutPullRequest(params: unknown): Promise<unknown>;
handleCheckoutPushRequest(params: unknown): Promise<unknown>;
handleCheckoutStatusRequest(params: unknown): Promise<unknown>;
@@ -1971,6 +1973,23 @@ describe("session checkout pull request merge", () => {
github: {
pullRequest: {
number: 42,
github: {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
},
}),
@@ -1988,8 +2007,33 @@ describe("session checkout pull request merge", () => {
cwd: "/tmp/request-worktree",
prNumber: 42,
mergeMethod: "squash",
status: {
number: 42,
github: {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
});
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(1, "/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "merge-pr-validation",
});
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(2, "/tmp/request-worktree", {
force: true,
reason: "merge-pr",
});
@@ -2005,6 +2049,131 @@ describe("session checkout pull request merge", () => {
});
});
test("rejects direct merge when fresh GitHub facts block a warm clean snapshot", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
mergePullRequest: vi.fn(
async (input: { status?: { github?: { mergeStateStatus?: string | null } } }) => {
if (input.status?.github?.mergeStateStatus === "BLOCKED") {
throw new Error("GitHub does not report this pull request as ready for direct merge");
}
return { success: true };
},
),
};
const createSnapshot = (mergeStateStatus: "CLEAN" | "BLOCKED") => ({
github: {
pullRequest: {
number: 42,
github: {
mergeStateStatus,
autoMergeRequest: null,
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
},
});
const workspaceGitService = {
getSnapshot: vi.fn(async (_cwd: string, options?: { force?: boolean }) =>
createSnapshot(options?.force ? "BLOCKED" : "CLEAN"),
),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutPrMergeRequest({
type: "checkout_pr_merge_request",
cwd: "/tmp/request-worktree",
mergeMethod: "squash",
requestId: "request-pr-merge-fresh-blocked",
});
expect(workspaceGitService.getSnapshot).toHaveBeenCalledTimes(1);
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "merge-pr-validation",
});
expect(github.mergePullRequest).toHaveBeenCalledWith(
expect.objectContaining({
status: expect.objectContaining({
github: expect.objectContaining({ mergeStateStatus: "BLOCKED" }),
}),
}),
);
expect(github.invalidate).not.toHaveBeenCalled();
expect(messages).toContainEqual({
type: "checkout_pr_merge_response",
payload: {
cwd: "/tmp/request-worktree",
success: false,
error: {
code: "UNKNOWN",
message: "GitHub does not report this pull request as ready for direct merge",
},
requestId: "request-pr-merge-fresh-blocked",
},
});
});
test("rejects direct merge when the current pull request is missing GitHub merge facts", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
mergePullRequest: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
mergeable: "MERGEABLE",
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutPrMergeRequest({
type: "checkout_pr_merge_request",
cwd: "/tmp/request-worktree",
mergeMethod: "squash",
requestId: "request-pr-merge-missing-github-facts",
});
expect(github.mergePullRequest).not.toHaveBeenCalled();
expect(github.invalidate).not.toHaveBeenCalled();
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "merge-pr-validation",
});
expect(messages).toContainEqual({
type: "checkout_pr_merge_response",
payload: {
cwd: "/tmp/request-worktree",
success: false,
error: {
code: "UNKNOWN",
message: "GitHub merge facts are unavailable for this pull request",
},
requestId: "request-pr-merge-missing-github-facts",
},
});
});
test("surfaces merge errors verbatim", async () => {
const messages: unknown[] = [];
const github = {
@@ -2016,6 +2185,23 @@ describe("session checkout pull request merge", () => {
github: {
pullRequest: {
number: 42,
github: {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
},
}),
@@ -2044,6 +2230,362 @@ describe("session checkout pull request merge", () => {
});
});
describe("session checkout pull request auto-merge", () => {
const autoMergeGithubFacts = (
overrides: Partial<GitHubPullRequestStatusFacts> = {},
): GitHubPullRequestStatusFacts => ({
mergeStateStatus: "BLOCKED",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
...overrides,
});
test("enables auto-merge for the current pull request and refreshes GitHub state", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
enablePullRequestAutoMerge: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
mergeable: "MERGEABLE",
github: autoMergeGithubFacts(),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: true,
mergeMethod: "squash",
requestId: "request-pr-auto-merge-enable",
});
expect(github.enablePullRequestAutoMerge).toHaveBeenCalledWith({
cwd: "/tmp/request-worktree",
prNumber: 42,
mergeMethod: "squash",
status: {
number: 42,
mergeable: "MERGEABLE",
github: autoMergeGithubFacts(),
},
});
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(1, "/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "auto-merge-validation",
});
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(2, "/tmp/request-worktree", {
force: true,
reason: "enable-pr-auto-merge",
});
expect(github.invalidate).toHaveBeenCalledWith({ cwd: "/tmp/request-worktree" });
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: true,
success: true,
error: null,
requestId: "request-pr-auto-merge-enable",
},
});
});
test("disables auto-merge for the current pull request and refreshes GitHub state", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
disablePullRequestAutoMerge: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
github: autoMergeGithubFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T17:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "moboudra",
},
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: true,
}),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: false,
requestId: "request-pr-auto-merge-disable",
});
expect(github.disablePullRequestAutoMerge).toHaveBeenCalledWith({
cwd: "/tmp/request-worktree",
prNumber: 42,
status: {
number: 42,
github: autoMergeGithubFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T17:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "moboudra",
},
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: true,
}),
},
});
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(1, "/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "auto-merge-validation",
});
expect(workspaceGitService.getSnapshot).toHaveBeenNthCalledWith(2, "/tmp/request-worktree", {
force: true,
reason: "disable-pr-auto-merge",
});
expect(github.invalidate).toHaveBeenCalledWith({ cwd: "/tmp/request-worktree" });
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: false,
success: true,
error: null,
requestId: "request-pr-auto-merge-disable",
},
});
});
test("surfaces auto-merge errors verbatim", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
enablePullRequestAutoMerge: vi.fn().mockRejectedValue(new Error("auto-merge is disabled")),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
github: autoMergeGithubFacts(),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: true,
mergeMethod: "merge",
requestId: "request-pr-auto-merge-failure",
});
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: true,
success: false,
error: {
code: "UNKNOWN",
message: "auto-merge is disabled",
},
requestId: "request-pr-auto-merge-failure",
},
});
});
test("rejects auto-merge enable when the requested method is disabled", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
enablePullRequestAutoMerge: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
github: autoMergeGithubFacts({
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: false,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "MERGE",
},
}),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: true,
mergeMethod: "squash",
requestId: "request-pr-auto-merge-method-disabled",
});
expect(github.enablePullRequestAutoMerge).not.toHaveBeenCalled();
expect(github.invalidate).not.toHaveBeenCalled();
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "auto-merge-validation",
});
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: true,
success: false,
error: {
code: "UNKNOWN",
message: "Auto-merge is not available because squash is disabled",
},
requestId: "request-pr-auto-merge-method-disabled",
},
});
});
test("rejects auto-merge disable when the viewer cannot disable it", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
disablePullRequestAutoMerge: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
github: autoMergeGithubFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T17:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "someone-else",
},
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
}),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: false,
requestId: "request-pr-auto-merge-disable-forbidden",
});
expect(github.disablePullRequestAutoMerge).not.toHaveBeenCalled();
expect(github.invalidate).not.toHaveBeenCalled();
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
force: true,
includeGitHub: true,
reason: "auto-merge-validation",
});
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: false,
success: false,
error: {
code: "UNKNOWN",
message: "GitHub does not allow this viewer to disable auto-merge",
},
requestId: "request-pr-auto-merge-disable-forbidden",
},
});
});
test("rejects auto-merge disable requests that include a merge method", async () => {
const messages: unknown[] = [];
const github = {
invalidate: vi.fn(),
disablePullRequestAutoMerge: vi.fn().mockResolvedValue({ success: true }),
};
const workspaceGitService = {
getSnapshot: vi.fn().mockResolvedValue({
github: {
pullRequest: {
number: 42,
github: autoMergeGithubFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T17:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "moboudra",
},
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: true,
}),
},
},
}),
};
const session = createSessionForTest({ github, workspaceGitService, messages });
await asSessionInternals(session).handleCheckoutGithubSetAutoMergeRequest({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/request-worktree",
enabled: false,
mergeMethod: "squash",
requestId: "request-pr-auto-merge-disable-with-method",
});
expect(github.disablePullRequestAutoMerge).not.toHaveBeenCalled();
expect(github.invalidate).not.toHaveBeenCalled();
expect(messages).toContainEqual({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd: "/tmp/request-worktree",
enabled: false,
success: false,
error: {
code: "UNKNOWN",
message: "mergeMethod is not allowed when disabling auto-merge",
},
requestId: "request-pr-auto-merge-disable-with-method",
},
});
});
});
describe("session checkout pull and push handling", () => {
test("forces workspace git and GitHub refresh after pulling", async () => {
const messages: unknown[] = [];
+115 -8
View File
@@ -82,7 +82,11 @@ import type { DaemonConfigStore } from "./daemon-config-store.js";
import { applyMutableProviderConfigToOverrides } from "./daemon-config-store.js";
import { getErrorMessage, getErrorMessageOr } from "../shared/error-utils.js";
import { getAgentStatusPriority } from "../shared/agent-state-bucket.js";
import type { WorkspaceGitRuntimeSnapshot, WorkspaceGitService } from "./workspace-git-service.js";
import type {
WorkspaceGitRuntimeSnapshot,
WorkspaceGitService,
WorkspaceGitSnapshotOptions,
} from "./workspace-git-service.js";
import { buildProviderRegistry } from "./agent/provider-registry.js";
import type {
@@ -211,6 +215,8 @@ import { LoopService } from "./loop-service.js";
import { ScheduleService } from "./schedule/service.js";
import { execCommand } from "../utils/spawn.js";
import {
assertPullRequestAutoMergeDisableReady,
assertPullRequestAutoMergeEnableReady,
createGitHubService,
type GitHubService,
type PullRequestTimelineItem,
@@ -242,6 +248,12 @@ import { toWorktreeWireError } from "./worktree-errors.js";
const WORKSPACE_GIT_WATCH_REMOVED_STATE_KEY = "__removed__";
type CurrentWorkspacePullRequest = NonNullable<
WorkspaceGitRuntimeSnapshot["github"]["pullRequest"]
> & {
number: number;
};
interface ResolveKnownProjectRootForConfigInput {
repoRoot: string;
projectRegistry: Pick<ProjectRegistry, "list">;
@@ -288,6 +300,8 @@ type GitMutationRefreshReason =
| "merge-to-base"
| "merge-from-base"
| "merge-pr"
| "enable-pr-auto-merge"
| "disable-pr-auto-merge"
| "create-pr"
| "switch-branch"
| "create-branch"
@@ -2013,6 +2027,8 @@ export class Session {
return this.handleCheckoutPrCreateRequest(msg);
case "checkout_pr_merge_request":
return this.handleCheckoutPrMergeRequest(msg);
case "checkout.github.set_auto_merge.request":
return this.handleCheckoutGithubSetAutoMergeRequest(msg);
case "checkout_pr_status_request":
return this.handleCheckoutPrStatusRequest(msg);
case "pull_request_timeline_request":
@@ -5180,16 +5196,17 @@ export class Session {
const { cwd, requestId } = msg;
try {
const snapshot = await this.workspaceGitService.getSnapshot(cwd);
const prNumber = snapshot.github.pullRequest?.number;
if (typeof prNumber !== "number") {
throw new Error("Unable to determine GitHub pull request number for merge");
}
const pullRequest = await this.resolveCurrentPullRequest(cwd, "merge", {
force: true,
includeGitHub: true,
reason: "merge-pr-validation",
});
this.assertCurrentPullRequestHasGithubMergeFacts(pullRequest);
await this.github.mergePullRequest({
cwd,
prNumber,
prNumber: pullRequest.number,
mergeMethod: msg.mergeMethod,
status: pullRequest,
});
await this.notifyGitMutation(cwd, "merge-pr", { invalidateGithub: true });
@@ -5215,6 +5232,96 @@ export class Session {
}
}
private assertCurrentPullRequestHasGithubMergeFacts(
pullRequest: CurrentWorkspacePullRequest,
): void {
if (!pullRequest.github) {
throw new Error("GitHub merge facts are unavailable for this pull request");
}
}
private async handleCheckoutGithubSetAutoMergeRequest(
msg: Extract<SessionInboundMessage, { type: "checkout.github.set_auto_merge.request" }>,
): Promise<void> {
const { cwd, requestId } = msg;
try {
const pullRequest = await this.resolveCurrentPullRequest(cwd, "auto-merge", {
force: true,
includeGitHub: true,
reason: "auto-merge-validation",
});
if (msg.enabled) {
const mergeMethod = msg.mergeMethod;
if (!mergeMethod) {
throw new Error("mergeMethod is required when enabling auto-merge");
}
assertPullRequestAutoMergeEnableReady({
mergeMethod,
status: pullRequest,
});
await this.github.enablePullRequestAutoMerge({
cwd,
prNumber: pullRequest.number,
mergeMethod,
status: pullRequest,
});
} else {
if (msg.mergeMethod) {
throw new Error("mergeMethod is not allowed when disabling auto-merge");
}
assertPullRequestAutoMergeDisableReady({ status: pullRequest });
await this.github.disablePullRequestAutoMerge({
cwd,
prNumber: pullRequest.number,
status: pullRequest,
});
}
await this.notifyGitMutation(
cwd,
msg.enabled ? "enable-pr-auto-merge" : "disable-pr-auto-merge",
{
invalidateGithub: true,
},
);
this.emit({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd,
enabled: msg.enabled,
success: true,
error: null,
requestId,
},
});
} catch (error) {
this.emit({
type: "checkout.github.set_auto_merge.response",
payload: {
cwd,
enabled: msg.enabled,
success: false,
error: toCheckoutError(error),
requestId,
},
});
}
}
private async resolveCurrentPullRequest(
cwd: string,
operation: "merge" | "auto-merge",
options?: WorkspaceGitSnapshotOptions,
): Promise<CurrentWorkspacePullRequest> {
const snapshot = await this.workspaceGitService.getSnapshot(cwd, options);
const pullRequest = snapshot.github.pullRequest;
if (!pullRequest || typeof pullRequest.number !== "number") {
throw new Error(`Unable to determine GitHub pull request number for ${operation}`);
}
return { ...pullRequest, number: pullRequest.number };
}
private async handleCheckoutPrStatusRequest(
msg: Extract<SessionInboundMessage, { type: "checkout_pr_status_request" }>,
): Promise<void> {
@@ -451,6 +451,23 @@ describe("workspace git watch targets", () => {
],
checksStatus: "success",
reviewDecision: "approved",
github: {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
error: null,
},
@@ -483,6 +500,23 @@ describe("workspace git watch targets", () => {
],
checksStatus: "success",
reviewDecision: "approved",
github: {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
},
githubFeaturesEnabled: true,
error: null,
@@ -1048,6 +1048,8 @@ export class VoiceAssistantWebSocketServer {
features: {
// COMPAT(providersSnapshot): keep optional until all clients rely on snapshot flow.
providersSnapshot: true,
// COMPAT(checkoutGithubSetAutoMerge): added in v0.1.75, remove gate after 2026-11-13.
checkoutGithubSetAutoMerge: true,
},
};
}
@@ -79,11 +79,11 @@ function createCheckoutStatus(
};
}
function createPullRequestStatusResult(): PullRequestStatusResult {
function createPullRequestStatusResult(title = "Update feature"): PullRequestStatusResult {
return {
status: {
url: "https://github.com/acme/repo/pull/123",
title: "Update feature",
title,
state: "open",
baseRefName: "main",
headRefName: "feature",
@@ -537,6 +537,61 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
service.dispose();
});
test("a forced GitHub-inclusive call during an in-flight forced git refresh queues a GitHub refresh", async () => {
const forcedGitRefresh = createDeferred<CheckoutStatusGit>();
const getCheckoutStatus = vi
.fn<() => Promise<CheckoutStatusGit>>()
.mockImplementationOnce(async () => forcedGitRefresh.promise)
.mockImplementation(async () => createCheckoutStatus(REPO_CWD));
const getPullRequestStatus = vi
.fn()
.mockResolvedValueOnce(createPullRequestStatusResult("Stale cached PR"))
.mockResolvedValueOnce(createPullRequestStatusResult("Fresh validation PR"));
const service = createService({ getCheckoutStatus, getPullRequestStatus });
const gitRefresh = service.getSnapshot(REPO_CWD, {
force: true,
includeGitHub: false,
reason: "watch",
});
await flushPromises();
const validationRefresh = service.getSnapshot(REPO_CWD, {
force: true,
includeGitHub: true,
reason: "merge-pr-validation",
});
await flushPromises();
expect(getCheckoutStatus).toHaveBeenCalledTimes(1);
forcedGitRefresh.resolve(createCheckoutStatus(REPO_CWD));
await expect(validationRefresh).resolves.toEqual(
createSnapshot(REPO_CWD, {
github: {
pullRequest: {
url: "https://github.com/acme/repo/pull/123",
title: "Fresh validation PR",
state: "open",
baseRefName: "main",
headRefName: "feature",
isMerged: false,
},
},
}),
);
await gitRefresh;
expect(getCheckoutStatus).toHaveBeenCalledTimes(2);
expect(getPullRequestStatus).toHaveBeenNthCalledWith(2, REPO_CWD, expect.anything(), {
force: true,
reason: "merge-pr-validation",
});
service.dispose();
});
test("ref-watch firing during an in-flight forced refresh does not produce an extra shell burst", async () => {
const forcedRefresh = createDeferred<CheckoutStatusGit>();
const getCheckoutStatus = vi
@@ -22,6 +22,7 @@ import {
} from "../utils/checkout-git.js";
import {
createGitHubService,
type GitHubPullRequestStatusFacts,
type GitHubService,
type PullRequestMergeable,
} from "../services/github-service.js";
@@ -92,6 +93,7 @@ export interface WorkspaceGitRuntimeSnapshot {
}>;
checksStatus?: "none" | "pending" | "success" | "failure";
reviewDecision?: "approved" | "changes_requested" | "pending" | null;
github?: GitHubPullRequestStatusFacts;
} | null;
error: { message: string } | null;
};
@@ -1324,7 +1326,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
request: WorkspaceGitRefreshRequest,
): Promise<WorkspaceGitRuntimeSnapshot> {
if (target.refreshState.status === "in-flight") {
if (request.force && !target.refreshState.force) {
const needsForcedRefresh = request.force && !target.refreshState.force;
const needsGitHubRefresh =
request.force && request.includeGitHub && !target.refreshState.includeGitHub;
if (needsForcedRefresh || needsGitHubRefresh) {
target.refreshState.queued = this.mergeQueuedRefresh(target.refreshState.queued, request);
}
return target.refreshState.promise;
@@ -1424,10 +1429,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
const force = queued.force || request.force;
const upgradesForce = request.force && !queued.force;
const upgradesGitHub = request.includeGitHub && !queued.includeGitHub;
return {
force,
includeGitHub: queued.includeGitHub || request.includeGitHub,
reason: request.force && !queued.force ? request.reason : queued.reason,
reason: upgradesForce || upgradesGitHub ? request.reason : queued.reason,
notify: queued.notify || request.notify,
};
}
@@ -115,6 +115,31 @@ function currentPullRequestJson(overrides: Record<string, unknown> = {}): string
});
}
function currentPullRequestGithubFactsJson(overrides: Record<string, unknown> = {}): string {
return JSON.stringify({
data: {
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: false,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
pullRequest: {
mergeStateStatus: "BLOCKED",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
...overrides,
},
},
});
}
function createCurrentPullRequestStatus(
overrides: Partial<GitHubCurrentPullRequestStatus> = {},
): GitHubCurrentPullRequestStatus {
@@ -137,6 +162,29 @@ function createCurrentPullRequestStatus(
};
}
function githubStatusFacts(
overrides: Partial<NonNullable<GitHubCurrentPullRequestStatus["github"]>> = {},
): NonNullable<GitHubCurrentPullRequestStatus["github"]> {
return {
mergeStateStatus: "CLEAN",
autoMergeRequest: null,
viewerCanEnableAutoMerge: false,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: false,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
...overrides,
};
}
function recordCurrentPullRequestStatusReads(service: ReturnType<typeof createGitHubService>) {
const reads: GitHubReadOptions[] = [];
const getCurrentPullRequestStatus = service.getCurrentPullRequestStatus.bind(service);
@@ -147,6 +195,12 @@ function recordCurrentPullRequestStatusReads(service: ReturnType<typeof createGi
return reads;
}
function currentPullRequestStatusCalls(calls: RunnerCall[]): RunnerCall[] {
return calls.filter(
(call) => call.args[0] === "pr" && (call.args[1] === "view" || call.args[1] === "list"),
);
}
function noPullRequestError(args: string[] = ["pr", "view"]): GitHubCommandError {
return new GitHubCommandError({
args,
@@ -314,6 +368,9 @@ describe("GitHubService", () => {
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod,
status: createCurrentPullRequestStatus({
github: githubStatusFacts(),
}),
}),
).resolves.toEqual({ success: true });
@@ -326,6 +383,196 @@ describe("GitHubService", () => {
]);
});
it("rejects direct merge when GitHub facts are unavailable", async () => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.mergePullRequest({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod: "squash",
status: createCurrentPullRequestStatus(),
}),
).rejects.toThrow("GitHub merge facts are unavailable");
expect(runner.calls).toEqual([]);
});
it.each(["BLOCKED", "DIRTY", null] as const)(
"rejects direct merge when GitHub mergeStateStatus is %s",
async (mergeStateStatus) => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.mergePullRequest({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod: "squash",
status: createCurrentPullRequestStatus({
github: githubStatusFacts({ mergeStateStatus }),
}),
}),
).rejects.toThrow("ready for direct merge");
expect(runner.calls).toEqual([]);
},
);
it.each([
["merge queue enabled", { isMergeQueueEnabled: true }],
["PR already in merge queue", { isInMergeQueue: true }],
] as const)("rejects direct merge when %s", async (_name, overrides) => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.mergePullRequest({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod: "squash",
status: createCurrentPullRequestStatus({
github: githubStatusFacts(overrides),
}),
}),
).rejects.toThrow("merge queue");
expect(runner.calls).toEqual([]);
});
it("rejects direct merge when auto-merge is already enabled", async () => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.mergePullRequest({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod: "squash",
status: createCurrentPullRequestStatus({
github: githubStatusFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T12:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "octocat",
},
}),
}),
}),
).rejects.toThrow("auto-merge is already enabled");
expect(runner.calls).toEqual([]);
});
it("rejects direct merge when the requested method is disabled by repository policy", async () => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.mergePullRequest({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod: "squash",
status: createCurrentPullRequestStatus({
github: githubStatusFacts({
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: false,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "MERGE",
},
}),
}),
}),
).rejects.toThrow("squash is disabled");
expect(runner.calls).toEqual([]);
});
it.each([
["merge", ["pr", "merge", "42", "--auto", "--merge"]],
["squash", ["pr", "merge", "42", "--auto", "--squash"]],
["rebase", ["pr", "merge", "42", "--auto", "--rebase"]],
] as const)("enables auto-merge with gh using %s", async (mergeMethod, expectedArgs) => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.enablePullRequestAutoMerge({
cwd: "/tmp/repo",
prNumber: 42,
mergeMethod,
status: createCurrentPullRequestStatus({
github: githubStatusFacts({
mergeStateStatus: "BLOCKED",
viewerCanEnableAutoMerge: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
}),
}),
}),
).resolves.toEqual({ success: true });
expect(runner.calls).toEqual([
{
args: expectedArgs,
cwd: "/tmp/repo",
envOverlay: { GH_PROMPT_DISABLED: "1" },
},
]);
});
it("disables auto-merge with gh", async () => {
const runner = createRunner([""]);
const service = createGitHubService({
runner: runner.runner,
});
await expect(
service.disablePullRequestAutoMerge({
cwd: "/tmp/repo",
prNumber: 42,
status: createCurrentPullRequestStatus({
github: githubStatusFacts({
autoMergeRequest: {
enabledAt: "2026-05-13T12:00:00Z",
mergeMethod: "SQUASH",
enabledBy: "octocat",
},
viewerCanDisableAutoMerge: true,
}),
}),
}),
).resolves.toEqual({ success: true });
expect(runner.calls).toEqual([
{
args: ["pr", "merge", "42", "--disable-auto"],
cwd: "/tmp/repo",
envOverlay: { GH_PROMPT_DISABLED: "1" },
},
]);
});
it("computes fast cadence for pending and slow cadence for stable PR states", () => {
const pendingStatus = createCurrentPullRequestStatus({ checksStatus: "pending" });
const runningCheckStatus = createCurrentPullRequestStatus({
@@ -408,7 +655,7 @@ describe("GitHubService", () => {
now = EXPECTED_GITHUB_FAST_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
expect(runner.calls).toHaveLength(2);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(2);
expect(reads.map((read) => read.reason)).toEqual([undefined, "self-heal-github"]);
subscription?.unsubscribe();
@@ -441,11 +688,11 @@ describe("GitHubService", () => {
now = EXPECTED_GITHUB_FAST_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
expect(runner.calls).toHaveLength(1);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
now = EXPECTED_GITHUB_SLOW_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS - EXPECTED_GITHUB_FAST_POLL_MS);
expect(runner.calls).toHaveLength(2);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(2);
expect(reads.map((read) => read.reason)).toEqual([undefined, "self-heal-github"]);
subscription?.unsubscribe();
@@ -458,14 +705,17 @@ describe("GitHubService", () => {
currentPullRequestJson({
statusCheckRollup: [{ __typename: "StatusContext", context: "ci", state: "PENDING" }],
}),
currentPullRequestGithubFactsJson(),
{ error: new Error("network down") },
{ error: new Error("network still down") },
currentPullRequestJson({
statusCheckRollup: [{ __typename: "StatusContext", context: "ci", state: "SUCCESS" }],
}),
currentPullRequestGithubFactsJson(),
currentPullRequestJson({
statusCheckRollup: [{ __typename: "StatusContext", context: "ci", state: "SUCCESS" }],
}),
currentPullRequestGithubFactsJson(),
]);
const service = createGitHubService({
ttlMs: 0,
@@ -490,7 +740,7 @@ describe("GitHubService", () => {
now += EXPECTED_GITHUB_SLOW_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
expect(runner.calls).toHaveLength(5);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(5);
expect(reads.map((read) => read.reason)).toEqual([
undefined,
"self-heal-github",
@@ -527,7 +777,7 @@ describe("GitHubService", () => {
now = EXPECTED_GITHUB_FAST_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
expect(runner.calls).toHaveLength(1);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
service.dispose?.();
});
@@ -553,7 +803,7 @@ describe("GitHubService", () => {
now = EXPECTED_GITHUB_FAST_POLL_MS;
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
expect(runner.calls).toHaveLength(1);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
});
it("fetches PR reviews and issue comments with one GraphQL call sorted chronologically", async () => {
@@ -1139,7 +1389,7 @@ describe("GitHubService", () => {
headRef: "feature/pr-pane",
});
expect(runner.calls.map((call) => call.args)).toEqual([
expect(runner.calls.slice(0, 2).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["pr", "view", "--json", CURRENT_PR_STATUS_BASE_FIELDS],
]);
@@ -1171,6 +1421,72 @@ describe("GitHubService", () => {
expect(status?.mergeable).toBe("UNKNOWN");
});
it("loads GitHub merge, auto-merge, permission, policy, and queue facts for PR 993 shape", async () => {
const runner = createScriptedRunner([
currentPullRequestJson({
number: 993,
url: "https://github.com/getpaseo/paseo/pull/993",
title: "Auto-merge UX",
headRefName: "github-pr-auto-merge-ux",
mergeable: "MERGEABLE",
reviewDecision: "APPROVED",
statusCheckRollup: [
{
__typename: "CheckRun",
name: "server tests",
workflowName: "CI",
status: "IN_PROGRESS",
conclusion: null,
detailsUrl: "https://github.com/getpaseo/paseo/actions/runs/993",
},
],
}),
currentPullRequestGithubFactsJson(),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
now: () => 100,
});
const status = await service.getCurrentPullRequestStatus({
cwd: "/repo",
headRef: "github-pr-auto-merge-ux",
});
expect(runner.calls.map((call) => call.args[0])).toEqual(["pr", "api"]);
expect(status).toMatchObject({
number: 993,
mergeable: "MERGEABLE",
checks: [
{
name: "server tests",
status: "pending",
url: "https://github.com/getpaseo/paseo/actions/runs/993",
workflow: "CI",
},
],
checksStatus: "pending",
github: {
mergeStateStatus: "BLOCKED",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: false,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
});
});
it("resolves fork PR heads to the parent repository when gh pr view returns a stale branch match", async () => {
const runner = createScriptedRunner([
currentPullRequestJson({
@@ -1231,7 +1547,7 @@ describe("GitHubService", () => {
title: "Real fork PR",
headRefName: "feature/fork",
});
expect(runner.calls.map((call) => call.args)).toEqual([
expect(runner.calls.slice(0, 3).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
[
@@ -1314,7 +1630,7 @@ describe("GitHubService", () => {
checks: [],
checksStatus: "none",
});
expect(runner.calls.map((call) => call.args)).toEqual([
expect(runner.calls.slice(0, 4).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
[
@@ -1452,7 +1768,7 @@ describe("GitHubService", () => {
repoName: "repo",
headRefName: "main",
});
expect(runner.calls.map((call) => call.args)).toEqual([
expect(runner.calls.slice(0, 2).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
[
"pr",
@@ -1978,13 +2294,15 @@ describe("GitHubService", () => {
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "feature/fork" }),
).resolves.toMatchObject({ number: 42 });
expect(runner.calls).toHaveLength(1);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
});
it("bypasses the warm PR status cache for forced reads", async () => {
const runner = createRunner([
currentPullRequestJson({ number: 41, title: "First" }),
currentPullRequestGithubFactsJson(),
currentPullRequestJson({ number: 42, title: "Forced" }),
currentPullRequestGithubFactsJson(),
]);
const service = createGitHubService({
runner: runner.runner,
@@ -2004,7 +2322,7 @@ describe("GitHubService", () => {
}),
).resolves.toMatchObject({ number: 42 });
expect(runner.calls).toHaveLength(2);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(2);
});
it("coalesces concurrent PR status callers", async () => {
@@ -2019,8 +2337,13 @@ describe("GitHubService", () => {
const second = service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "feature/fork" });
await Promise.resolve();
expect(runner.calls).toHaveLength(1);
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
runner.resolveNext(currentPullRequestJson());
for (let i = 0; i < 10 && runner.calls.length < 2; i += 1) {
await Promise.resolve();
}
expect(runner.calls[1]?.args[0]).toBe("api");
runner.resolveNext(currentPullRequestGithubFactsJson());
await expect(Promise.all([first, second])).resolves.toEqual([
expect.objectContaining({ number: 42 }),
+345 -1
View File
@@ -93,6 +93,52 @@ const HeadRepositoryOwnerSchema = z
const PullRequestMergeableSchema = z.enum(["MERGEABLE", "CONFLICTING", "UNKNOWN"]).catch("UNKNOWN");
const GitHubAutoMergeRequestSchema = z
.object({
enabledAt: z.string().nullable().optional().catch(null),
mergeMethod: z.string().nullable().optional().catch(null),
enabledBy: z
.object({
login: z.string().nullable().optional().catch(null),
})
.nullable()
.optional()
.catch(null),
})
.nullable()
.optional()
.catch(null);
const GitHubPullRequestFactsGraphqlSchema = z.object({
data: z.object({
repository: z
.object({
autoMergeAllowed: z.boolean().optional().catch(false),
mergeCommitAllowed: z.boolean().optional().catch(false),
squashMergeAllowed: z.boolean().optional().catch(false),
rebaseMergeAllowed: z.boolean().optional().catch(false),
viewerDefaultMergeMethod: z.string().nullable().optional().catch(null),
pullRequest: z
.object({
mergeStateStatus: z.string().nullable().optional().catch(null),
autoMergeRequest: GitHubAutoMergeRequestSchema,
viewerCanEnableAutoMerge: z.boolean().optional().catch(false),
viewerCanDisableAutoMerge: z.boolean().optional().catch(false),
viewerCanMergeAsAdmin: z.boolean().optional().catch(false),
viewerCanUpdateBranch: z.boolean().optional().catch(false),
isMergeQueueEnabled: z.boolean().optional().catch(false),
isInMergeQueue: z.boolean().optional().catch(false),
})
.nullable()
.optional()
.catch(null),
})
.nullable()
.optional()
.catch(null),
}),
});
const CurrentPullRequestStatusSchema = z.object({
number: z.number().optional(),
url: z.string().catch(""),
@@ -240,6 +286,33 @@ const CURRENT_PR_STATUS_BASE_FIELDS =
"number,url,title,state,isDraft,baseRefName,headRefName,mergedAt,reviewDecision,mergeable,headRepositoryOwner";
const CURRENT_PR_STATUS_FIELDS = `${CURRENT_PR_STATUS_BASE_FIELDS},statusCheckRollup`;
const PULL_REQUEST_STATUS_FACTS_QUERY = `
query PullRequestStatusFacts($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
autoMergeAllowed
mergeCommitAllowed
squashMergeAllowed
rebaseMergeAllowed
viewerDefaultMergeMethod
pullRequest(number: $number) {
mergeStateStatus
autoMergeRequest {
enabledAt
mergeMethod
enabledBy {
login
}
}
viewerCanEnableAutoMerge
viewerCanDisableAutoMerge
viewerCanMergeAsAdmin
viewerCanUpdateBranch
isMergeQueueEnabled
isInMergeQueue
}
}
}`;
const PULL_REQUEST_TIMELINE_QUERY = `
query PullRequestTimeline($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
@@ -353,6 +426,28 @@ export type PullRequestChecksStatus = "none" | "pending" | "success" | "failure"
export type PullRequestReviewDecision = "approved" | "changes_requested" | "pending" | null;
export type PullRequestMergeable = "MERGEABLE" | "CONFLICTING" | "UNKNOWN";
export interface GitHubPullRequestStatusFacts {
mergeStateStatus: string | null;
autoMergeRequest: {
enabledAt: string | null;
mergeMethod: string | null;
enabledBy: string | null;
} | null;
viewerCanEnableAutoMerge: boolean;
viewerCanDisableAutoMerge: boolean;
viewerCanMergeAsAdmin: boolean;
viewerCanUpdateBranch: boolean;
repository: {
autoMergeAllowed: boolean;
mergeCommitAllowed: boolean;
squashMergeAllowed: boolean;
rebaseMergeAllowed: boolean;
viewerDefaultMergeMethod: string | null;
};
isMergeQueueEnabled: boolean;
isInMergeQueue: boolean;
}
export interface GitHubCurrentPullRequestStatus {
number?: number;
repoOwner?: string;
@@ -368,6 +463,7 @@ export interface GitHubCurrentPullRequestStatus {
checks: PullRequestCheck[];
checksStatus: PullRequestChecksStatus;
reviewDecision: PullRequestReviewDecision;
github?: GitHubPullRequestStatusFacts;
}
export type PullRequestTimelineReviewState = "approved" | "changes_requested" | "commented";
@@ -412,17 +508,41 @@ export interface GitHubPullRequestCreateResult {
}
export type GitHubPullRequestMergeMethod = "merge" | "squash" | "rebase";
const DIRECT_PULL_REQUEST_MERGE_STATE_ALLOWLIST = new Set(["CLEAN", "HAS_HOOKS"]);
export interface GitHubPullRequestCommandStatus {
mergeable?: PullRequestMergeable;
github?: GitHubPullRequestStatusFacts;
}
export interface MergeGitHubPullRequestOptions {
cwd: string;
prNumber: number;
mergeMethod: GitHubPullRequestMergeMethod;
status?: GitHubPullRequestCommandStatus | null;
}
export interface EnableGitHubPullRequestAutoMergeOptions {
cwd: string;
prNumber: number;
mergeMethod: GitHubPullRequestMergeMethod;
status?: GitHubPullRequestCommandStatus | null;
}
export interface DisableGitHubPullRequestAutoMergeOptions {
cwd: string;
prNumber: number;
status?: GitHubPullRequestCommandStatus | null;
}
export interface GitHubPullRequestMergeResult {
success: true;
}
export interface GitHubPullRequestAutoMergeResult {
success: true;
}
export type GitHubReadOptions =
| {
force?: false;
@@ -512,6 +632,12 @@ export interface GitHubService {
options: CreateGitHubPullRequestOptions,
): Promise<GitHubPullRequestCreateResult>;
mergePullRequest(options: MergeGitHubPullRequestOptions): Promise<GitHubPullRequestMergeResult>;
enablePullRequestAutoMerge(
options: EnableGitHubPullRequestAutoMergeOptions,
): Promise<GitHubPullRequestAutoMergeResult>;
disablePullRequestAutoMerge(
options: DisableGitHubPullRequestAutoMergeOptions,
): Promise<GitHubPullRequestAutoMergeResult>;
isAuthenticated(options: { cwd: string } & GitHubReadOptions): Promise<boolean>;
retainCurrentPullRequestStatusPoll?(options: {
cwd: string;
@@ -577,6 +703,13 @@ interface CommandFailureLike {
type PullRequestCheckRunNode = z.infer<typeof PullRequestCheckRunNodeSchema>;
type PullRequestStatusContextNode = z.infer<typeof PullRequestStatusContextNodeSchema>;
type CurrentPullRequestStatusItem = z.infer<typeof CurrentPullRequestStatusSchema>;
type GitHubPullRequestFactsGraphql = z.infer<typeof GitHubPullRequestFactsGraphqlSchema>;
type GitHubPullRequestFactsRepository = NonNullable<
GitHubPullRequestFactsGraphql["data"]["repository"]
>;
type GitHubPullRequestFactsPullRequest = NonNullable<
GitHubPullRequestFactsRepository["pullRequest"]
>;
interface InFlightCacheEntry {
cwd: string;
@@ -882,12 +1015,13 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
},
readOptions: input,
load: async () => {
return resolveCurrentPullRequestView({
const status = await resolveCurrentPullRequestView({
cwd: input.cwd,
headRef: input.headRef,
headRepositoryOwner: input.headRepositoryOwner,
run,
});
return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run });
},
}).then((status) => {
updatePollTargetAfterSuccess({
@@ -1051,6 +1185,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
},
async mergePullRequest(input) {
assertDirectPullRequestMergeReady(input);
await run(["pr", "merge", String(input.prNumber), `--${input.mergeMethod}`], {
cwd: input.cwd,
envOverlay: { GH_PROMPT_DISABLED: "1" },
@@ -1058,6 +1193,24 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
return { success: true };
},
async enablePullRequestAutoMerge(input) {
assertPullRequestAutoMergeEnableReady(input);
await run(["pr", "merge", String(input.prNumber), "--auto", `--${input.mergeMethod}`], {
cwd: input.cwd,
envOverlay: { GH_PROMPT_DISABLED: "1" },
});
return { success: true };
},
async disablePullRequestAutoMerge(input) {
assertPullRequestAutoMergeDisableReady(input);
await run(["pr", "merge", String(input.prNumber), "--disable-auto"], {
cwd: input.cwd,
envOverlay: { GH_PROMPT_DISABLED: "1" },
});
return { success: true };
},
isAuthenticated(input) {
return cached({
cwd: input.cwd,
@@ -1161,6 +1314,89 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
return api;
}
function assertDirectPullRequestMergeReady(input: MergeGitHubPullRequestOptions): void {
const github = input.status?.github;
if (!github) {
throw new Error("GitHub merge facts are unavailable for this pull request");
}
if (!DIRECT_PULL_REQUEST_MERGE_STATE_ALLOWLIST.has(github.mergeStateStatus ?? "")) {
throw new Error("GitHub does not report this pull request as ready for direct merge");
}
if (github.isMergeQueueEnabled || github.isInMergeQueue) {
throw new Error("Direct merge is not available because this repository uses a merge queue");
}
if (github.autoMergeRequest !== null) {
throw new Error("Direct merge is not available because auto-merge is already enabled");
}
if (!isPullRequestMergeMethodAllowed(github.repository, input.mergeMethod)) {
throw new Error(`Direct merge is not available because ${input.mergeMethod} is disabled`);
}
}
export function assertPullRequestAutoMergeEnableReady(
input: Pick<EnableGitHubPullRequestAutoMergeOptions, "mergeMethod" | "status">,
): void {
const github = input.status?.github;
if (!github) {
throw new Error("GitHub auto-merge facts are unavailable for this pull request");
}
if (github.mergeStateStatus !== "BLOCKED") {
throw new Error("GitHub does not report this pull request as blocked for auto-merge");
}
if (!github.viewerCanEnableAutoMerge) {
throw new Error("GitHub does not allow this viewer to enable auto-merge");
}
if (!github.repository.autoMergeAllowed) {
throw new Error("Auto-merge is disabled for this repository");
}
if (!isPullRequestMergeMethodAllowed(github.repository, input.mergeMethod)) {
throw new Error(`Auto-merge is not available because ${input.mergeMethod} is disabled`);
}
if (github.autoMergeRequest !== null) {
throw new Error("Auto-merge is already enabled for this pull request");
}
if (github.isMergeQueueEnabled || github.isInMergeQueue) {
throw new Error("Auto-merge is not available because this repository uses a merge queue");
}
if (input.status?.mergeable === "CONFLICTING") {
throw new Error("Auto-merge is not available because this pull request has conflicts");
}
}
export function assertPullRequestAutoMergeDisableReady(
input: Pick<DisableGitHubPullRequestAutoMergeOptions, "status">,
): void {
const github = input.status?.github;
if (!github) {
throw new Error("GitHub auto-merge facts are unavailable for this pull request");
}
if (github.autoMergeRequest === null) {
throw new Error("Auto-merge is not enabled for this pull request");
}
if (!github.viewerCanDisableAutoMerge) {
throw new Error("GitHub does not allow this viewer to disable auto-merge");
}
if (github.isMergeQueueEnabled || github.isInMergeQueue) {
throw new Error("Auto-merge is not available because this repository uses a merge queue");
}
}
export function isPullRequestMergeMethodAllowed(
repository: GitHubPullRequestStatusFacts["repository"],
method: GitHubPullRequestMergeMethod,
): boolean {
if (method === "squash") {
return repository.squashMergeAllowed;
}
if (method === "merge") {
return repository.mergeCommitAllowed;
}
return repository.rebaseMergeAllowed;
}
export function computeGithubNextInterval(
status: GitHubCurrentPullRequestStatus | null,
consecutiveErrors: number,
@@ -1372,6 +1608,68 @@ async function resolveCurrentPullRequestView(options: {
return match?.status ?? null;
}
async function addCurrentPullRequestGithubFacts(options: {
cwd: string;
status: GitHubCurrentPullRequestStatus | null;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<GitHubCurrentPullRequestStatus | null> {
const { status } = options;
if (!status?.repoOwner || !status.repoName || typeof status.number !== "number") {
return status;
}
const facts = await loadPullRequestGithubFacts({
cwd: options.cwd,
owner: status.repoOwner,
name: status.repoName,
number: status.number,
run: options.run,
});
if (!facts) {
return status;
}
return {
...status,
github: facts,
};
}
async function loadPullRequestGithubFacts(options: {
cwd: string;
owner: string;
name: string;
number: number;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<GitHubPullRequestStatusFacts | null> {
try {
const stdout = await options.run(
[
"api",
"graphql",
"-f",
`query=${PULL_REQUEST_STATUS_FACTS_QUERY}`,
"-F",
`owner=${options.owner}`,
"-F",
`name=${options.name}`,
"-F",
`number=${options.number}`,
],
{ cwd: options.cwd },
);
return parsePullRequestGithubFacts(stdout);
} catch (error) {
if (
error instanceof GitHubCommandError ||
error instanceof z.ZodError ||
error instanceof SyntaxError
) {
return null;
}
throw error;
}
}
async function tryCurrentPullRequestView(options: {
cwd: string;
headRef: string;
@@ -1469,6 +1767,52 @@ function parseCurrentPullRequestCandidateList(
.filter((candidate): candidate is ResolvedPullRequestCandidate => candidate !== null);
}
function parsePullRequestGithubFacts(stdout: string): GitHubPullRequestStatusFacts | null {
const parsed = GitHubPullRequestFactsGraphqlSchema.parse(JSON.parse(stdout || "{}"));
const repository = parsed.data.repository;
const pullRequest = repository?.pullRequest;
if (!repository || !pullRequest) {
return null;
}
return {
mergeStateStatus: pullRequest.mergeStateStatus ?? null,
autoMergeRequest: toGitHubAutoMergeRequest(pullRequest.autoMergeRequest),
viewerCanEnableAutoMerge: pullRequest.viewerCanEnableAutoMerge ?? false,
viewerCanDisableAutoMerge: pullRequest.viewerCanDisableAutoMerge ?? false,
viewerCanMergeAsAdmin: pullRequest.viewerCanMergeAsAdmin ?? false,
viewerCanUpdateBranch: pullRequest.viewerCanUpdateBranch ?? false,
repository: toGitHubRepositoryMergePolicy(repository),
isMergeQueueEnabled: pullRequest.isMergeQueueEnabled ?? false,
isInMergeQueue: pullRequest.isInMergeQueue ?? false,
};
}
function toGitHubAutoMergeRequest(
request: GitHubPullRequestFactsPullRequest["autoMergeRequest"],
): GitHubPullRequestStatusFacts["autoMergeRequest"] {
if (!request) {
return null;
}
return {
enabledAt: request.enabledAt ?? null,
mergeMethod: request.mergeMethod ?? null,
enabledBy: request.enabledBy?.login ?? null,
};
}
function toGitHubRepositoryMergePolicy(
repository: GitHubPullRequestFactsRepository,
): GitHubPullRequestStatusFacts["repository"] {
return {
autoMergeAllowed: repository.autoMergeAllowed ?? false,
mergeCommitAllowed: repository.mergeCommitAllowed ?? false,
squashMergeAllowed: repository.squashMergeAllowed ?? false,
rebaseMergeAllowed: repository.rebaseMergeAllowed ?? false,
viewerDefaultMergeMethod: repository.viewerDefaultMergeMethod ?? null,
};
}
function toCurrentPullRequestCandidate(
item: CurrentPullRequestStatusItem,
fallbackHeadRefName: string,
@@ -1,6 +1,12 @@
import { describe, expect, test } from "vitest";
import { CheckoutPrMergeRequestSchema, CheckoutPrStatusSchema } from "./messages.js";
import {
CheckoutGithubSetAutoMergeRequestSchema,
CheckoutGithubSetAutoMergeResponseSchema,
CheckoutPrMergeRequestSchema,
CheckoutPrStatusSchema,
ServerInfoStatusPayloadSchema,
} from "./messages.js";
describe("checkout PR schemas", () => {
test("parses PR status payloads without mergeability", () => {
@@ -20,6 +26,67 @@ describe("checkout PR schemas", () => {
});
});
test("keeps missing provider-specific GitHub PR facts absent for old daemons", () => {
const parsed = CheckoutPrStatusSchema.parse({
number: 42,
url: "https://github.com/getpaseo/paseo/pull/42",
title: "Ship it",
state: "open",
baseRefName: "main",
headRefName: "feature/ship-it",
isMerged: false,
mergeable: "MERGEABLE",
});
expect(parsed.github).toBeUndefined();
});
test("parses provider-specific GitHub PR status facts", () => {
expect(
CheckoutPrStatusSchema.parse({
number: 993,
url: "https://github.com/getpaseo/paseo/pull/993",
title: "Block direct merge while checks run",
state: "open",
baseRefName: "main",
headRefName: "phase-2",
isMerged: false,
mergeable: "MERGEABLE",
checks: [{ name: "server tests", status: "pending", url: null }],
checksStatus: "pending",
github: {
mergeStateStatus: "BLOCKED",
autoMergeRequest: null,
viewerCanEnableAutoMerge: true,
viewerCanDisableAutoMerge: false,
viewerCanMergeAsAdmin: false,
viewerCanUpdateBranch: true,
repository: {
autoMergeAllowed: true,
mergeCommitAllowed: false,
squashMergeAllowed: true,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: "SQUASH",
},
isMergeQueueEnabled: false,
isInMergeQueue: false,
},
}),
).toMatchObject({
mergeable: "MERGEABLE",
checksStatus: "pending",
github: {
mergeStateStatus: "BLOCKED",
viewerCanEnableAutoMerge: true,
repository: {
autoMergeAllowed: true,
squashMergeAllowed: true,
viewerDefaultMergeMethod: "SQUASH",
},
},
});
});
test.each(["merge", "squash", "rebase"] as const)(
"accepts %s as a PR merge method",
(mergeMethod) => {
@@ -44,4 +111,79 @@ describe("checkout PR schemas", () => {
}),
).toThrow();
});
test.each(["merge", "squash", "rebase"] as const)(
"accepts %s as a GitHub set-auto-merge enable method",
(mergeMethod) => {
expect(
CheckoutGithubSetAutoMergeRequestSchema.parse({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/repo",
enabled: true,
mergeMethod,
requestId: "request-enable-auto-merge",
}),
).toMatchObject({ enabled: true, mergeMethod });
},
);
test("rejects unknown GitHub set-auto-merge enable methods", () => {
expect(() =>
CheckoutGithubSetAutoMergeRequestSchema.parse({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/repo",
enabled: true,
mergeMethod: "auto",
requestId: "request-enable-auto-merge",
}),
).toThrow();
});
test("accepts GitHub set-auto-merge disable requests", () => {
expect(
CheckoutGithubSetAutoMergeRequestSchema.parse({
type: "checkout.github.set_auto_merge.request",
cwd: "/tmp/repo",
enabled: false,
requestId: "request-disable-auto-merge",
}),
).toMatchObject({
cwd: "/tmp/repo",
enabled: false,
requestId: "request-disable-auto-merge",
});
});
test("accepts GitHub set-auto-merge responses", () => {
const payload = {
cwd: "/tmp/repo",
enabled: true,
success: true,
error: null,
requestId: "request-auto-merge",
};
expect(
CheckoutGithubSetAutoMergeResponseSchema.parse({
type: "checkout.github.set_auto_merge.response",
payload,
}).payload,
).toEqual(payload);
});
test("accepts the GitHub auto-merge server_info feature flag", () => {
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv_test",
features: {
providersSnapshot: true,
checkoutGithubSetAutoMerge: true,
},
}).features,
).toEqual({
providersSnapshot: true,
checkoutGithubSetAutoMerge: true,
});
});
});
+70
View File
@@ -1314,6 +1314,14 @@ export const CheckoutPrMergeRequestSchema = z.object({
requestId: z.string(),
});
export const CheckoutGithubSetAutoMergeRequestSchema = z.object({
type: z.literal("checkout.github.set_auto_merge.request"),
cwd: z.string(),
enabled: z.boolean(),
mergeMethod: z.enum(["merge", "squash", "rebase"]).optional(),
requestId: z.string(),
});
export const CheckoutPrStatusRequestSchema = z.object({
type: z.literal("checkout_pr_status_request"),
cwd: z.string(),
@@ -1763,6 +1771,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPushRequestSchema,
CheckoutPrCreateRequestSchema,
CheckoutPrMergeRequestSchema,
CheckoutGithubSetAutoMergeRequestSchema,
CheckoutPrStatusRequestSchema,
PullRequestTimelineRequestSchema,
CheckoutSwitchBranchRequestSchema,
@@ -1985,6 +1994,7 @@ export const ServerInfoStatusPayloadSchema = z
features: z
.object({
providersSnapshot: z.boolean().optional(),
checkoutGithubSetAutoMerge: z.boolean().optional(),
})
.optional(),
})
@@ -2705,6 +2715,47 @@ export const CheckoutStatusResponseSchema = z.object({
]),
});
const CheckoutPrGithubAutoMergeRequestSchema = z
.object({
enabledAt: z.string().nullable().optional().default(null),
mergeMethod: z.string().nullable().optional().default(null),
enabledBy: z.string().nullable().optional().default(null),
})
.nullable()
.optional()
.default(null);
const CheckoutPrGithubRepositoryPolicySchema = z
.object({
autoMergeAllowed: z.boolean().optional().default(false),
mergeCommitAllowed: z.boolean().optional().default(false),
squashMergeAllowed: z.boolean().optional().default(false),
rebaseMergeAllowed: z.boolean().optional().default(false),
viewerDefaultMergeMethod: z.string().nullable().optional().default(null),
})
.optional()
.default({
autoMergeAllowed: false,
mergeCommitAllowed: false,
squashMergeAllowed: false,
rebaseMergeAllowed: false,
viewerDefaultMergeMethod: null,
});
const CheckoutPrGithubStatusSchema = z
.object({
mergeStateStatus: z.string().nullable().optional().default(null),
autoMergeRequest: CheckoutPrGithubAutoMergeRequestSchema,
viewerCanEnableAutoMerge: z.boolean().optional().default(false),
viewerCanDisableAutoMerge: z.boolean().optional().default(false),
viewerCanMergeAsAdmin: z.boolean().optional().default(false),
viewerCanUpdateBranch: z.boolean().optional().default(false),
repository: CheckoutPrGithubRepositoryPolicySchema,
isMergeQueueEnabled: z.boolean().optional().default(false),
isInMergeQueue: z.boolean().optional().default(false),
})
.optional();
export const CheckoutPrStatusSchema = z.object({
number: z.number().optional(),
url: z.string(),
@@ -2735,6 +2786,7 @@ export const CheckoutPrStatusSchema = z.object({
reviewDecision: z.string().nullable().optional(),
repoOwner: z.string().optional(),
repoName: z.string().optional(),
github: CheckoutPrGithubStatusSchema,
});
const CheckoutPrStatusPayloadSchema = z.object({
@@ -2850,6 +2902,17 @@ export const CheckoutPrMergeResponseSchema = z.object({
}),
});
export const CheckoutGithubSetAutoMergeResponseSchema = z.object({
type: z.literal("checkout.github.set_auto_merge.response"),
payload: z.object({
cwd: z.string(),
enabled: z.boolean(),
success: z.boolean(),
error: CheckoutErrorSchema.nullable(),
requestId: z.string(),
}),
});
export const CheckoutPrStatusResponseSchema = z.object({
type: z.literal("checkout_pr_status_response"),
payload: CheckoutPrStatusPayloadSchema,
@@ -3408,6 +3471,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPushResponseSchema,
CheckoutPrCreateResponseSchema,
CheckoutPrMergeResponseSchema,
CheckoutGithubSetAutoMergeResponseSchema,
CheckoutPrStatusResponseSchema,
PullRequestTimelineResponseSchema,
CheckoutSwitchBranchResponseSchema,
@@ -3664,6 +3728,12 @@ export type CheckoutPrCreateResponse = z.infer<typeof CheckoutPrCreateResponseSc
export type CheckoutPrMergeRequest = z.infer<typeof CheckoutPrMergeRequestSchema>;
export type CheckoutPrMergeResponse = z.infer<typeof CheckoutPrMergeResponseSchema>;
export type CheckoutPrMergeMethod = z.infer<typeof CheckoutPrMergeRequestSchema>["mergeMethod"];
export type CheckoutGithubSetAutoMergeRequest = z.infer<
typeof CheckoutGithubSetAutoMergeRequestSchema
>;
export type CheckoutGithubSetAutoMergeResponse = z.infer<
typeof CheckoutGithubSetAutoMergeResponseSchema
>;
export type PullRequestMergeable = z.infer<typeof CheckoutPrStatusSchema>["mergeable"];
export type CheckoutPrStatusRequest = z.infer<typeof CheckoutPrStatusRequestSchema>;
export type CheckoutPrStatusResponse = z.infer<typeof CheckoutPrStatusResponseSchema>;
@@ -1708,6 +1708,30 @@ const x = 1;
expect(callCount).toBe(1);
});
it("passes forced PR status reads through to the GitHub service", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
cwd: repoDir,
});
const requested: Array<{ force?: boolean; reason?: string }> = [];
const github = createGitHubServiceForStatus(null);
github.getCurrentPullRequestStatus = async (options) => {
requested.push({
...(options.force ? { force: options.force } : {}),
...(options.reason ? { reason: options.reason } : {}),
});
return createPullRequestStatus();
};
await getPullRequestStatus(repoDir, github, {
force: true,
reason: "merge-pr-validation",
});
expect(requested).toEqual([{ force: true, reason: "merge-pr-validation" }]);
});
it("expires cached PR status after the TTL", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
@@ -1777,6 +1801,39 @@ const x = 1;
}
});
it("does not use stale PR status fallback for forced GitHub errors", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
cwd: repoDir,
});
const github = createGitHubServiceForStatus(null);
github.getCurrentPullRequestStatus = async () =>
createPullRequestStatus({
url: "https://github.com/getpaseo/paseo/pull/123",
});
const fresh = await getPullRequestStatus(repoDir, github);
expect(fresh.status?.url).toContain("/pull/123");
const error = new GitHubCommandError({
args: ["pr", "view"],
cwd: repoDir,
exitCode: 1,
stderr: "could not resolve host: github.com",
});
github.getCurrentPullRequestStatus = async () => {
throw error;
};
await expect(
getPullRequestStatus(repoDir, github, {
force: true,
reason: "merge-pr-validation",
}),
).rejects.toBe(error);
});
it("clears stale PR status after a successful no-PR refresh", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
+23 -6
View File
@@ -11,6 +11,8 @@ import {
GitHubCommandError,
createGitHubService,
resolveGitHubRepo,
type GitHubCurrentPullRequestStatus,
type GitHubPullRequestStatusFacts,
type GitHubService,
type PullRequestMergeable,
} from "../services/github-service.js";
@@ -2318,6 +2320,7 @@ export interface PullRequestStatus {
checks?: PullRequestCheck[];
checksStatus?: ChecksStatus;
reviewDecision?: ReviewDecision;
github?: GitHubPullRequestStatusFacts;
}
export interface PullRequestStatusResult {
@@ -2402,7 +2405,7 @@ export async function getPullRequestStatus(
return status;
})
.catch((error) => {
if (error instanceof GitHubCommandError) {
if (!options?.force && error instanceof GitHubCommandError) {
const stale = lastSuccessfulPullRequestStatus.get(cacheKey);
if (stale) {
return stale;
@@ -2433,11 +2436,25 @@ async function getPullRequestStatusUncached(
}
try {
const lookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head);
const status = await github.getCurrentPullRequestStatus({
cwd,
...lookupTarget,
reason: options?.reason,
});
let status: GitHubCurrentPullRequestStatus | null;
if (options?.force) {
const reason = options.reason;
if (!reason) {
throw new Error("Forced PR status read requires a reason");
}
status = await github.getCurrentPullRequestStatus({
cwd,
...lookupTarget,
force: true,
reason,
});
} else {
status = await github.getCurrentPullRequestStatus({
cwd,
...lookupTarget,
reason: options?.reason,
});
}
return {
status,
githubFeaturesEnabled: true,