Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/server/src/fetchers.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,16 @@ vi.mock("./github-client.js", () => ({
}),
}));

const cacheTimes = new Map<string, number>();
vi.mock("./cache.js", () => ({
getCached: (key: string) => cacheStore.get(key) ?? null,
setCached: (key: string, data: unknown) => {
cacheStore.set(key, data);
cacheTimes.set(key, Date.now());
},
cacheAge: (key: string) => {
const t = cacheTimes.get(key);
return t == null ? null : Date.now() - t;
},
}));
Comment on lines +26 to 37

Expand Down
9 changes: 7 additions & 2 deletions packages/server/src/fetchers.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { Octokit } from "@octokit/rest";
import { getCached, setCached } from "./cache.js";
import { cacheAge, getCached, setCached } from "./cache.js";
import { getClient, getInstance } from "./github-client.js";

interface RepoSettings {
autoMergeAllowed: boolean;
}

const inFlightRepoSettings = new Map<string, Promise<RepoSettings>>();
const REPO_SETTINGS_TTL_MS = 2 * 60 * 1000;

export async function getRepoSettings(
client: Octokit,
Expand All @@ -15,7 +16,11 @@ export async function getRepoSettings(
repo: string,
): Promise<RepoSettings> {
const key = `${instanceId}:repo-settings:${owner}/${repo}`;
const cached = getCached<RepoSettings>(key);
const age = cacheAge(key);
const cached =
age !== null && age < REPO_SETTINGS_TTL_MS
? getCached<RepoSettings>(key)
: null;
if (cached) return cached;
const existing = inFlightRepoSettings.get(key);
if (existing) return existing;
Expand Down
5 changes: 3 additions & 2 deletions packages/server/src/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ describe("POST /:instanceId/prs/:owner/:repo/:prNumber/merge", () => {
expect(fetchersStub.fetchRecentPrs).toHaveBeenCalledWith("github");
});

it("forwards GitHub's first error line when merge is rejected", async () => {
it("forwards GitHub's full error message (joining non-empty lines) when merge is rejected", async () => {
const ghErr = Object.assign(new Error("405"), {
status: 405,
response: {
Expand All @@ -368,7 +368,8 @@ describe("POST /:instanceId/prs/:owner/:repo/:prNumber/merge", () => {
expect(res.status).toBe(422);
expect(await res.json()).toEqual({
error: "merge_rejected",
message: "Repository rule violations found",
message:
"Repository rule violations found — A conversation must be resolved before this pull request can be merged.",
});
});
});
Expand Down
17 changes: 12 additions & 5 deletions packages/server/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,12 +289,19 @@ api.post("/:instanceId/prs/:owner/:repo/:prNumber/merge", async (c) => {
merge_method: "squash",
});
} catch (err) {
// GitHub returns helpful messages here ("A conversation must be
// resolved…", "At least 1 approving review is required…"). Forward
// the first line so the toast is actionable.
// GitHub's message is often multi-line: a generic header
// ("Repository rule violations found") followed by the actionable
// detail ("A conversation must be resolved…"). Join non-empty lines
// so the toast carries the reason, not just the header.
const e = err as { response?: { data?: { message?: string } } };
const message =
e.response?.data?.message?.split("\n")[0] ?? "Failed to merge PR";
const raw = e.response?.data?.message;
const message = raw
? raw
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0)
.join(" — ")
: "Failed to merge PR";
return c.json({ error: "merge_rejected", message }, 422);
}

Expand Down
129 changes: 129 additions & 0 deletions packages/web/src/mutations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { QueryClient } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AutoMergeNotAllowedError } from "./api";

vi.mock("./api", async () => {
const actual = await vi.importActual<typeof import("./api")>("./api");
return {
...actual,
api: {
mergePr: vi.fn(),
toggleAutoMerge: vi.fn(),
},
};
});

vi.mock("sonner", () => ({
toast: Object.assign(vi.fn(), {
success: vi.fn(),
error: vi.fn(),
}),
}));

import { api } from "./api";
import { mergePr } from "./mutations";
import { toast } from "sonner";
import type { PR } from "./types";

const mergePrMock = vi.mocked(api.mergePr);
const toggleAutoMergeMock = vi.mocked(api.toggleAutoMerge);
const toastSuccess = vi.mocked(toast.success);
const toastError = vi.mocked(toast.error);

const target = {
instanceId: "github",
repo: "o/r",
number: 42,
title: "Add thing",
url: "https://github.com/o/r/pull/42",
};

function basePr(overrides: Partial<PR> = {}): PR {
return {
id: 1,
number: 42,
title: "Add thing",
body: "",
url: "https://github.com/o/r/pull/42",
repo: "o/r",
updatedAt: "2026-04-30T00:00:00Z",
author: "anton",
authorAvatar: "",
draft: false,
ciStatus: "success",
inMergeQueue: false,
autoMerge: false,
headBranch: "feat",
baseBranch: "main",
reviews: { approved: [], changesRequested: [] },
additions: 1,
deletions: 0,
commits: 1,
commentCount: 0,
labels: [],
...overrides,
};
}

describe("mergePr", () => {
let qc: QueryClient;

beforeEach(() => {
qc = new QueryClient();
qc.setQueryData(["prs", "github"], [basePr()]);
});

afterEach(() => {
vi.clearAllMocks();
});

it("merges successfully and shows success toast", async () => {
mergePrMock.mockResolvedValue({ ok: true });
await mergePr(qc, target);
expect(mergePrMock).toHaveBeenCalledWith("github", "o/r", 42);
expect(toggleAutoMergeMock).not.toHaveBeenCalled();
expect(toastSuccess).toHaveBeenCalledWith("PR merged");
expect(toastError).not.toHaveBeenCalled();
});

it("falls back to arming auto-merge when direct merge fails", async () => {
mergePrMock.mockRejectedValue(
new Error(
"Repository rule violations found — A conversation must be resolved",
),
);
toggleAutoMergeMock.mockResolvedValue({ ok: true, autoMerge: true });

await mergePr(qc, target);

expect(toggleAutoMergeMock).toHaveBeenCalledWith("github", "o/r", 42);
expect(toastSuccess).toHaveBeenCalledWith(
expect.stringContaining("Auto-merge enabled"),
);
expect(toastError).not.toHaveBeenCalled();

// PR is restored to the cache and now flagged autoMerge=true
const prs = qc.getQueryData<PR[]>(["prs", "github"]);
expect(prs).toHaveLength(1);
expect(prs?.[0]?.autoMerge).toBe(true);
});

it("surfaces the original merge error when repo doesn't allow auto-merge", async () => {
const mergeErr = new Error(
"Repository rule violations found — required reviews missing",
);
mergePrMock.mockRejectedValue(mergeErr);
toggleAutoMergeMock.mockRejectedValue(new AutoMergeNotAllowedError());

await expect(mergePr(qc, target)).rejects.toThrow(mergeErr);

expect(toggleAutoMergeMock).toHaveBeenCalledWith("github", "o/r", 42);
expect(toastError).toHaveBeenCalledWith(mergeErr.message);
expect(toastSuccess).not.toHaveBeenCalled();

// PR is restored to the cache, autoMerge unchanged
const prs = qc.getQueryData<PR[]>(["prs", "github"]);
expect(prs).toHaveLength(1);
expect(prs?.[0]?.autoMerge).toBe(false);
});
});
23 changes: 22 additions & 1 deletion packages/web/src/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,28 @@ export async function mergePr(
restore(qc, prsSnap);
restore(qc, reviewsSnap);
restore(qc, recentSnap);
toast.error(err instanceof Error ? err.message : "Failed to merge PR");

// mergeStateStatus="CLEAN" can lie when repo rulesets impose extra
// requirements GraphQL doesn't reflect. Always attempt to arm
// auto-merge as a fallback — the server returns AutoMergeNotAllowedError
// when the repo really disallows it (more reliable than the cached
// autoMergeAllowed flag, which can be stale).
const reason = err instanceof Error ? err.message : "Failed to merge PR";
try {
await api.toggleAutoMerge(target.instanceId, target.repo, target.number);
qc.setQueriesData<PR[]>({ queryKey: ["prs"] }, (old) =>
old?.map((pr) =>
matches(target)(pr) ? { ...pr, autoMerge: true } : pr,
),
);
Comment on lines +112 to +117
Comment on lines +113 to +117
toast.success(`Auto-merge enabled — direct merge blocked: ${reason}`);
return;
} catch {
// Fallback failed (repo doesn't allow auto-merge, or some other
// error) — surface the original merge error since that's what the
// user tried to do.
}
toast.error(reason);
throw err;
}
}
Expand Down
Loading