mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-17 13:54:54 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15071640ce | ||
|
|
efd7c5cc53 | ||
|
|
7931027162 | ||
|
|
220d4cb546 | ||
|
|
9e4806e615 | ||
|
|
45e2869ad8 | ||
|
|
35d0edb67b | ||
|
|
9dc32bb549 | ||
|
|
fedb40d112 | ||
|
|
7e5ea17d6c |
+19
-6
@@ -97,12 +97,25 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
- `matchesHost` from manifest `cloudHosts`
|
||||
- `probeHost` when self-hosted/Enterprise detection is supported
|
||||
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
Current change-request lookup prefers an open request for the branch and repository.
|
||||
A closed or merged request belongs to a workspace only when its checkout commit
|
||||
is in the forge's PR/MR commit list. Commits inherited from the base do not count.
|
||||
Display and auto-archive share this rule, preserving squash-merged requests and
|
||||
requests updated remotely while rejecting a fresh workspace on their base commit.
|
||||
A rewritten or newly advanced checkout no longer matches the terminal request.
|
||||
|
||||
Commit membership stays in the server snapshot; clients receive the selected
|
||||
request without its commit list. Archive uses that same evidence after refreshing
|
||||
the workspace. It still requires an observed open-to-merged transition and the
|
||||
workspace safety checks; being behind alone does not block it.
|
||||
|
||||
Containment spawns no Git commands and fetches no Git objects. GitHub loads only terminal
|
||||
commit IDs in a separate batch under the same rate budget, newest page first,
|
||||
and remembers pages by PR head. Open requests need no membership read. GitLab,
|
||||
Gitea, and legacy GitHub cache successful terminal commit lists by request head;
|
||||
failed reads stay retryable and reject the lookup, preserving its previous snapshot. A failed
|
||||
GitHub commit batch does not block workspaces whose status is already complete.
|
||||
Missing membership evidence leaves the workspace active.
|
||||
|
||||
Keep checkout HEAD in adapter cache and poll identities so checkout changes
|
||||
refresh the facts used by archive eligibility.
|
||||
|
||||
@@ -31,6 +31,7 @@ function createPullRequest(
|
||||
baseRefName: "main",
|
||||
headRefName: "feature",
|
||||
headSha: "same-head",
|
||||
commitOids: ["same-head"],
|
||||
isMerged: true,
|
||||
...overrides,
|
||||
};
|
||||
@@ -349,7 +350,7 @@ afterEach(() => {
|
||||
|
||||
describe("archiveIfSafe", () => {
|
||||
test("denies archive when checkout facts do not establish safety", async () => {
|
||||
for (const git of [{ headSha: undefined }, { behindOfOrigin: 1 }, { isDirty: null }]) {
|
||||
for (const git of [{ headSha: undefined }, { isDirty: null }]) {
|
||||
const harness = createHarness({ snapshot: createSnapshot({ git }) });
|
||||
await runArchiveIfSafe(harness);
|
||||
expect(harness.deps.archiveByScope).not.toHaveBeenCalled();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { pullRequestContainsCommit } from "../../services/pull-request-contains-commit.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentManager } from "../agent/agent-manager.js";
|
||||
@@ -65,8 +66,8 @@ export async function archiveIfSafe(input: {
|
||||
|
||||
if (
|
||||
!pullRequest?.isMerged ||
|
||||
!pullRequest.headSha ||
|
||||
!snapshot.git.headSha ||
|
||||
snapshot.git.headSha !== pullRequest.headSha ||
|
||||
snapshot.forge.error
|
||||
) {
|
||||
return;
|
||||
@@ -74,13 +75,18 @@ export async function archiveIfSafe(input: {
|
||||
if (snapshot.git.isDirty !== false) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) ||
|
||||
(snapshot.git.behindOfOrigin !== null && snapshot.git.behindOfOrigin !== 0)
|
||||
) {
|
||||
if (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!pullRequestContainsCommit({
|
||||
workspaceCommit: snapshot.git.headSha,
|
||||
pullRequestCommits: pullRequest.commitOids,
|
||||
})
|
||||
)
|
||||
return;
|
||||
|
||||
const ownership = await deps.isPaseoOwnedWorktreeCwd(cwd, {
|
||||
paseoHome: options.paseoHome,
|
||||
worktreesRoot: options.paseoWorktreesBaseRoot,
|
||||
|
||||
@@ -179,6 +179,7 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
});
|
||||
let observation: PullRequestObservation | null = null;
|
||||
let remoteHeadSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
|
||||
const workspaceHeadSha = remoteHeadSha;
|
||||
const reads: Array<string | undefined> = [];
|
||||
const archives: string[] = [];
|
||||
let archiveDecisions = 0;
|
||||
@@ -194,6 +195,7 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
status: observation && {
|
||||
...observation,
|
||||
headSha: remoteHeadSha,
|
||||
commitOids: [workspaceHeadSha, remoteHeadSha],
|
||||
title: observation.headRefName,
|
||||
baseRefName: "main",
|
||||
isMerged: observation.state === "merged",
|
||||
@@ -260,7 +262,23 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
metrics: () => service.getMetrics(),
|
||||
isActive: () => active,
|
||||
advanceRemoteHead: () => {
|
||||
remoteHeadSha = "a".repeat(40);
|
||||
remoteHeadSha = execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit-tree",
|
||||
"HEAD^{tree}",
|
||||
"-p",
|
||||
"HEAD",
|
||||
"-m",
|
||||
"remote update",
|
||||
],
|
||||
{ cwd, encoding: "utf8" },
|
||||
).trim();
|
||||
run(cwd, ["update-ref", "refs/remotes/origin/workspace", remoteHeadSha]);
|
||||
},
|
||||
makeDirty: () => writeFileSync(path.join(cwd, "README.md"), "uncommitted work\n"),
|
||||
commitUnpushed: () => {
|
||||
@@ -307,7 +325,7 @@ describe("workspace auto-archive behavior", () => {
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps a merged PR visible and the workspace active when its remote head advances", async () => {
|
||||
test("archives a clean workspace contained in the advanced merged PR head", async () => {
|
||||
const workspace = await createUnobservedWorkspace();
|
||||
const open = await workspace.observe("open");
|
||||
workspace.advanceRemoteHead();
|
||||
@@ -315,8 +333,9 @@ describe("workspace auto-archive behavior", () => {
|
||||
await vi.waitFor(() => expect(workspace.archiveDecisions()).toBe(1));
|
||||
expect(merged.forge.pullRequest?.url).toBe(open.forge.pullRequest?.url);
|
||||
expect(merged.forge.pullRequest?.headSha).not.toBe(merged.git.headSha);
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
expect(workspace.archives).toEqual([]);
|
||||
expect(merged.git.behindOfOrigin).toBe(1);
|
||||
expect(workspace.isActive()).toBe(false);
|
||||
expect(workspace.archives).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("archives a clean owned workspace on an unobserved open-to-merged transition only once", async () => {
|
||||
|
||||
@@ -51,6 +51,7 @@ describe("checkout status projection", () => {
|
||||
const payload = normalizeCheckoutPrStatusPayload(
|
||||
{
|
||||
number: 123,
|
||||
commitOids: ["server-only-membership"],
|
||||
repoOwner: "internal-owner",
|
||||
repoName: "internal-repo",
|
||||
url: "https://github.com/getpaseo/paseo/pull/123",
|
||||
@@ -76,6 +77,7 @@ describe("checkout status projection", () => {
|
||||
"github",
|
||||
);
|
||||
|
||||
expect(payload).not.toHaveProperty("commitOids");
|
||||
expect(payload).toHaveProperty("repoOwner", "internal-owner");
|
||||
expect(payload).toHaveProperty("repoName", "internal-repo");
|
||||
expect(payload).toHaveProperty("forge", "github");
|
||||
|
||||
@@ -6188,9 +6188,17 @@ export class Session {
|
||||
private buildWorkspaceGitHubRuntimePayload(
|
||||
snapshot: WorkspaceGitRuntimeSnapshot,
|
||||
): NonNullable<WorkspaceDescriptorPayload["githubRuntime"]> {
|
||||
if (!snapshot.forge.pullRequest) {
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest: null,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
const { commitOids: _commitOids, ...pullRequest } = snapshot.forge.pullRequest;
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest: snapshot.forge.pullRequest,
|
||||
pullRequest,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -201,6 +201,8 @@ export interface WorkspaceGitRuntimeSnapshot {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable?: PullRequestMergeable;
|
||||
|
||||
@@ -129,6 +129,8 @@ export interface CurrentPullRequestStatus {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable: PullRequestMergeable;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js";
|
||||
@@ -2048,6 +2050,8 @@ describe("createGiteaService", () => {
|
||||
if (args[0] === "pr" && args[1] === "list" && argValue(args, "--state") === "open") {
|
||||
return ok(JSON.stringify([]));
|
||||
}
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2067,6 +2071,38 @@ describe("createGiteaService", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows commit pagination headers and stops without probing past the last page", async () => {
|
||||
const closed = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "feature",
|
||||
headSha: "remote-head",
|
||||
});
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/pulls?")) return ok(JSON.stringify([closed]));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
const page = new URL(args[1], "https://gitea.test").searchParams.get("page");
|
||||
if (page === "1")
|
||||
return {
|
||||
stdout: JSON.stringify([{ sha: "other" }]),
|
||||
stderr: 'HTTP/1.1 200 OK\nLink: <https://gitea.test/commits?page=2>; rel="next"\n',
|
||||
};
|
||||
if (page === "2") return ok(JSON.stringify([{ sha: "own" }]));
|
||||
throw new Error("HTTP 500: page past end");
|
||||
}
|
||||
throw new Error("Unexpected call");
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8 });
|
||||
expect(calls.filter((args) => args[1]?.includes("/commits?"))).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses tea repository context when origin identity is unavailable", async () => {
|
||||
const headSha = "8888888888888888888888888888888888888888";
|
||||
const closedPr = currentPullRequestApi({
|
||||
@@ -2078,6 +2114,8 @@ describe("createGiteaService", () => {
|
||||
const { service, calls } = makeService(
|
||||
(args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].startsWith("repos/{owner}/{repo}/pulls?")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2100,15 +2138,20 @@ describe("createGiteaService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "dev",
|
||||
headSha: "1111111111111111111111111111111111111111",
|
||||
headSha: pullRequestCommit,
|
||||
merged: true,
|
||||
});
|
||||
const { service } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: workspaceCommit }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([stale]));
|
||||
}
|
||||
@@ -2117,9 +2160,9 @@ describe("createGiteaService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
cwd,
|
||||
headRef: "dev",
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
headSha: workspaceCommit,
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8, state: "merged" });
|
||||
});
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { CHECK_TRAIT_ACTION_REQUIRED, CHECK_TRAIT_WARNING } from "@getpaseo/protocol/check-traits";
|
||||
import { mapGiteaCommitState } from "@getpaseo/protocol/gitea-status";
|
||||
@@ -163,6 +167,7 @@ const GiteaPrListItemSchema = z
|
||||
labels: z.string().optional(),
|
||||
ci: z.string().optional(),
|
||||
headSha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
@@ -1399,6 +1404,7 @@ function throwFirstNonTeaAuthSearchRejection(results: PromiseSettledResult<unkno
|
||||
}
|
||||
|
||||
export function createGiteaService(options: CreateGiteaServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runTeaCommand;
|
||||
const resolveTea = createCachedCliPathResolver(options.resolveTeaPath ?? resolveTeaPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -1406,19 +1412,25 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
const now = options.now ?? Date.now;
|
||||
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
async function runResult(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
): Promise<TeaCommandResult> {
|
||||
const teaPath = await resolveTea();
|
||||
if (!teaPath) {
|
||||
throw new TeaCliMissingError();
|
||||
}
|
||||
try {
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
return await runner(args, runOptions);
|
||||
} catch (error) {
|
||||
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
return (await runResult(args, runOptions)).stdout.trim();
|
||||
}
|
||||
|
||||
function runJsonParse<T>(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
@@ -1594,7 +1606,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const status = toCurrentPullRequestStatus(match);
|
||||
const status = { ...toCurrentPullRequestStatus(match), commitOids: match.commitOids };
|
||||
return loadCurrentPullRequestChecks(input.cwd, match, status);
|
||||
}
|
||||
|
||||
@@ -1656,17 +1668,47 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
// owner gate.
|
||||
return input.headSha !== undefined && item.head.sha === input.headSha;
|
||||
});
|
||||
const match =
|
||||
candidates.find((item) => mapGiteaState(item.state) === "open") ??
|
||||
candidates.find(
|
||||
(item) =>
|
||||
mapGiteaState(item.state) !== "open" &&
|
||||
input.headSha !== undefined &&
|
||||
item.head.sha === input.headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? currentPullRequestApiToListItem(match) : null;
|
||||
const open = candidates.find((candidate) => mapGiteaState(candidate.state) === "open");
|
||||
if (open) return currentPullRequestApiToListItem(open);
|
||||
candidates.sort(
|
||||
(left, right) =>
|
||||
Number(right.head.sha === input.headSha) - Number(left.head.sha === input.headSha),
|
||||
);
|
||||
for (const item of candidates) {
|
||||
const commitOids = await readRequestCommits(
|
||||
`${input.cwd}:${repoPath}/${item.number}@${item.head.sha}`,
|
||||
async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const args = [
|
||||
"api",
|
||||
`${repoPath}/pulls/${item.number}/commits?limit=50&page=${page}&files=false&verification=false`,
|
||||
"--include",
|
||||
];
|
||||
const response = await runResult(args, { cwd: input.cwd });
|
||||
const commits = runJsonParse(
|
||||
args,
|
||||
{ cwd: input.cwd },
|
||||
response.stdout,
|
||||
z.array(z.object({ sha: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.sha));
|
||||
// tea writes response headers to stderr. Following Link also respects
|
||||
// server-side page caps and avoids probing beyond the final page.
|
||||
if (!/<[^>]+>;\s*rel="next"/i.test(response.stderr)) return result;
|
||||
}
|
||||
},
|
||||
);
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: input.headSha,
|
||||
pullRequestCommits: commitOids,
|
||||
})
|
||||
) {
|
||||
return { ...currentPullRequestApiToListItem(item), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function findOpenPullRequestForHeadRef(
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { createPullRequestCommitReader } from "./pull-request-contains-commit.js";
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -218,6 +221,21 @@ function currentPullRequestJson(overrides: Record<string, unknown> = {}): string
|
||||
});
|
||||
}
|
||||
|
||||
function commitPageJson(commitOids: string[]): Record<string, unknown> {
|
||||
return {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: commitOids.map((oid) => ({ commit: { oid } })),
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function directCommitsJson(commitOids: string[]): string {
|
||||
return JSON.stringify({ data: { repository: commitPageJson(commitOids) } });
|
||||
}
|
||||
|
||||
function currentPullRequestGithubFactsJson(overrides: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({
|
||||
data: {
|
||||
@@ -1111,6 +1129,252 @@ describe("ForgeService", () => {
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects failed commit reads and retries without retaining the failure", async () => {
|
||||
const read = createPullRequestCommitReader();
|
||||
await expect(
|
||||
read("bad@head", async () => {
|
||||
throw new Error("offline");
|
||||
}),
|
||||
).rejects.toThrow("offline");
|
||||
await expect(read("good@head", async () => ["own-commit"])).resolves.toEqual(["own-commit"]);
|
||||
await expect(read("bad@head", async () => ["recovered"])).resolves.toEqual(["recovered"]);
|
||||
await expect(
|
||||
read("good@head", async () => {
|
||||
throw new Error("must use cache");
|
||||
}),
|
||||
).resolves.toEqual(["own-commit"]);
|
||||
});
|
||||
|
||||
it.each(["transport", "alias"])(
|
||||
"preserves a failed workspace even with an older match and isolates a complete open workspace (%s)",
|
||||
async (failure) => {
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
number: 60,
|
||||
headRefName: "a",
|
||||
}),
|
||||
batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
}),
|
||||
]),
|
||||
t1: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ headRefName: "b", state: "OPEN", mergedAt: null }),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: { nodes: [], pageInfo: { hasPreviousPage: true, startCursor: "next" } },
|
||||
},
|
||||
},
|
||||
t1: commitPageJson(["own-a"]),
|
||||
}),
|
||||
failure === "transport"
|
||||
? { error: new Error("HTTP 502") }
|
||||
: batchPollStatusJson({ t0: null }),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const errorsA: unknown[] = [],
|
||||
errorsB: unknown[] = [];
|
||||
const statusesA: Array<CurrentPullRequestStatus | null> = [];
|
||||
const statusesB: Array<CurrentPullRequestStatus | null> = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onError: (error) => errorsA.push(error),
|
||||
onStatus: (status) => statusesA.push(status),
|
||||
});
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/b",
|
||||
headRef: "b",
|
||||
headSha: "own-b",
|
||||
onError: (error) => errorsB.push(error),
|
||||
onStatus: (status) => statusesB.push(status),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
service.dispose?.();
|
||||
expect(errorsA).toHaveLength(1);
|
||||
expect(statusesA).toEqual([]);
|
||||
expect(errorsB).toEqual([]);
|
||||
expect(statusesB).toEqual([expect.objectContaining({ state: "open" })]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cached", "failed-lower", "paged-lower", "pending-higher"])(
|
||||
"ignores a lower-ranked unresolved PR after the preferred match (%s)",
|
||||
async (scenario) => {
|
||||
let now = 0;
|
||||
const cold = true;
|
||||
const pendingHigher = scenario === "pending-higher";
|
||||
const own = batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
});
|
||||
const older = batchPollPrNodeJson({ number: 42, headRefName: "a" });
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) }),
|
||||
...(cold
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: pendingHigher ? "another" : "own-a" } }],
|
||||
pageInfo: {
|
||||
hasPreviousPage: pendingHigher,
|
||||
startCursor: pendingHigher ? "next" : null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
t1:
|
||||
scenario === "failed-lower" || pendingHigher
|
||||
? null
|
||||
: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "other" } }],
|
||||
pageInfo: { hasPreviousPage: true, startCursor: "older-page" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(pendingHigher
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "own-a" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
...(scenario === "cached"
|
||||
? [batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) })]
|
||||
: []),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
now: () => now,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [],
|
||||
errors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
if (scenario === "cached") {
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
}
|
||||
service.dispose?.();
|
||||
expect(errors).toEqual([]);
|
||||
expect(statuses).toHaveLength(scenario === "cached" ? 2 : 1);
|
||||
expect(statuses.every((status) => status?.number === 50)).toBe(true);
|
||||
expect(
|
||||
runner.calls.filter(({ args }) => args.join(" ").includes("PaseoBatchCommitPages")),
|
||||
).toHaveLength(Number(cold) + Number(pendingHigher));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"filters terminal PRs in a batched poll (pagination: %s)",
|
||||
async (paginate) => {
|
||||
vi.useRealTimers();
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
headRefName: "feature",
|
||||
headRefOid: pullRequestCommit,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: paginate ? "other" : workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: paginate, startCursor: "cursor-1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(paginate
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: "cursor-2" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
onTestFinished(() => service.dispose?.());
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const subscription = service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd,
|
||||
headRef: "feature",
|
||||
headSha: workspaceCommit,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
});
|
||||
onTestFinished(() => subscription?.unsubscribe());
|
||||
await vi.waitFor(() => expect(statuses).toHaveLength(1));
|
||||
expect(statuses[0]).toMatchObject({ state: "merged", headSha: pullRequestCommit });
|
||||
expect(runner.calls).toHaveLength(paginate ? 4 : 3);
|
||||
expect(runner.calls[0]?.args[3]).not.toContain("commits(");
|
||||
expect(runner.calls[1]?.args[3]).toContain("commits(last:100");
|
||||
expect(
|
||||
runner.calls.every((call) => call.args[0] === "api" && call.args[1] === "graphql"),
|
||||
).toBe(true);
|
||||
expect(history.git(["rev-parse", "HEAD"])).toBe(workspaceCommit);
|
||||
expect(history.git(["rev-parse", "@{upstream}"])).toBe(workspaceCommit);
|
||||
expect(() => history.git(["rev-parse", "--verify", "FETCH_HEAD"])).toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("batches PR status polls across workspaces into one GraphQL request", async () => {
|
||||
let now = 0;
|
||||
const runner = createScriptedRunner([
|
||||
@@ -1132,6 +1396,7 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1187,7 +1452,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1214,7 +1479,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(statusesA).toHaveLength(2);
|
||||
expect(statusesA[1]).toEqual(expect.objectContaining({ number: 41, checksStatus: "success" }));
|
||||
|
||||
@@ -1248,6 +1513,7 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([]),
|
||||
t1: batchPollChecksAliasJson([]),
|
||||
@@ -1291,7 +1557,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1491,6 +1757,7 @@ describe("ForgeService", () => {
|
||||
t0: batchPollRepositoryJson([], { isFork: true, parent }),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1532,7 +1799,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls[3]?.args[3]).toContain(
|
||||
expect(runner.calls[4]?.args[3]).toContain(
|
||||
't0: repository(owner: "upstream", name: "widgets")',
|
||||
);
|
||||
|
||||
@@ -1611,6 +1878,83 @@ describe("ForgeService", () => {
|
||||
service.dispose?.();
|
||||
});
|
||||
|
||||
it.each(["reserve", "error"])(
|
||||
"preserves known checks when commit paging pauses the host (%s)",
|
||||
async (failure) => {
|
||||
let now = 0;
|
||||
const open = batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ state: "OPEN", mergedAt: null, headRefName: "open" }),
|
||||
]);
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: open }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "FAILURE" },
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: open,
|
||||
t1: batchPollRepositoryJson([batchPollPrNodeJson()]),
|
||||
}),
|
||||
...(failure === "reserve"
|
||||
? [
|
||||
batchPollStatusWithRateLimitJson({
|
||||
aliases: {},
|
||||
limit: 5000,
|
||||
remaining: 0,
|
||||
resetAt: new Date(3600000).toISOString(),
|
||||
}),
|
||||
]
|
||||
: [
|
||||
{
|
||||
error: Object.assign(new Error("gh exited 1"), {
|
||||
code: 1,
|
||||
stderr: "GraphQL: API rate limit already exceeded for user ID 123",
|
||||
}),
|
||||
},
|
||||
JSON.stringify({ resources: { graphql: { remaining: 0, reset: 3600 } } }),
|
||||
]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
ttlMs: 3600000,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
now: () => now,
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const errors: unknown[] = [],
|
||||
terminalErrors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/open",
|
||||
headRef: "open",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/terminal",
|
||||
headRef: "feat-a",
|
||||
headSha: "oid-42",
|
||||
onError: (error) => terminalErrors.push(error),
|
||||
});
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(terminalErrors).toHaveLength(1);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/open", headRef: "open" }),
|
||||
).resolves.toMatchObject({ checksStatus: "failure" });
|
||||
expect(runner.calls).toHaveLength(failure === "reserve" ? 4 : 5);
|
||||
service.dispose?.();
|
||||
},
|
||||
);
|
||||
|
||||
it("pauses a host until reset when a batch reaches the GraphQL reserve", async () => {
|
||||
let now = 0;
|
||||
const resetAt = new Date(EXPECTED_GITHUB_ERROR_BACKOFF_CAP_MS).toISOString();
|
||||
@@ -1717,6 +2061,7 @@ describe("ForgeService", () => {
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([closedNode]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-closed"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "PENDING" },
|
||||
@@ -1748,7 +2093,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(statuses).toEqual([expect.objectContaining({ number: 9, checksStatus: "pending" })]);
|
||||
|
||||
// Pending checks are never frozen, so the next cycle re-runs the checks
|
||||
@@ -1757,7 +2102,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls).toHaveLength(5);
|
||||
expect(statuses[1]).toEqual(expect.objectContaining({ number: 9, checksStatus: "success" }));
|
||||
|
||||
subscription?.unsubscribe();
|
||||
@@ -1870,6 +2215,7 @@ describe("ForgeService", () => {
|
||||
stderr: "GraphQL: Could not resolve to a Repository",
|
||||
}),
|
||||
},
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1902,7 +2248,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(statuses).toEqual([
|
||||
expect.objectContaining({ number: 41, state: "merged", checksStatus: "success" }),
|
||||
]);
|
||||
@@ -3138,6 +3484,42 @@ describe("ForgeService", () => {
|
||||
expect(details.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("chooses an open PR before reading an older terminal candidate's commits", async () => {
|
||||
const terminal = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 1,
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const open = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 2,
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(terminal),
|
||||
JSON.stringify({ owner: { login: "acme" }, name: "repo", parent: null }),
|
||||
JSON.stringify([open, terminal]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 2, state: "open" });
|
||||
expect(runner.calls.some(({ args }) => args.join(" ").includes("commits(last:"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retries current PR view without statusCheckRollup when token permissions are insufficient", async () => {
|
||||
const runner = createScriptedRunner([
|
||||
{
|
||||
@@ -3280,12 +3662,16 @@ describe("ForgeService", () => {
|
||||
|
||||
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
|
||||
const headSha = "2222222222222222222222222222222222222222";
|
||||
const runner = createRunner([
|
||||
currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
}),
|
||||
const candidate = currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
directCommitsJson([headSha]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3296,6 +3682,7 @@ describe("ForgeService", () => {
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headSha,
|
||||
headRepositoryOwner: "forkOwner",
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(42);
|
||||
@@ -3303,16 +3690,20 @@ describe("ForgeService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestJson({
|
||||
headRepositoryOwner: { login: "parentOwner" },
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: "1111111111111111111111111111111111111111",
|
||||
headRefOid: pullRequestCommit,
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
stale,
|
||||
JSON.stringify({ owner: { login: "parentOwner" }, name: "parentRepo", parent: null }),
|
||||
JSON.stringify([JSON.parse(stale)]),
|
||||
directCommitsJson([workspaceCommit, pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3321,9 +3712,9 @@ describe("ForgeService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
cwd,
|
||||
headRef: "feature/fork",
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
headSha: workspaceCommit,
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(runner.calls.some((call) => call.args[0] === "pr" && call.args[1] === "list")).toBe(
|
||||
@@ -3331,7 +3722,117 @@ describe("ForgeService", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers an exact terminal head and otherwise the most recently updated terminal PR", async () => {
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when a reused branch is ahead of its head",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
mergedAt: state === "MERGED" ? "2026-07-17T12:00:00Z" : null,
|
||||
headRefOid: history.workspaceCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.workspaceCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.remote,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.pullRequestCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when the workspace only shares its inherited base",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
headRefOid: history.pullRequestCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.cwd,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.workspaceCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("reads only commit IDs for a cold terminal lookup and reuses the list", async () => {
|
||||
const candidate = currentPullRequestJson({
|
||||
number: 987,
|
||||
state: "MERGED",
|
||||
headRefOid: "cold-own-head",
|
||||
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "cold-own-head" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: "cold-own-head",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 987 });
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls.filter((call) => call.args[3]?.includes("commits(last:100"))).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(runner.calls[0]?.args.at(-1)).not.toContain("commits");
|
||||
expect(runner.calls[2]?.args[3]).toContain("commits(last:100");
|
||||
expect(runner.calls[2]?.args[3]).not.toContain("authors");
|
||||
});
|
||||
|
||||
it("rejects an unrelated terminal PR on a reused branch", async () => {
|
||||
const owner = { login: "forkOwner" };
|
||||
const terminal = ({
|
||||
number,
|
||||
@@ -3368,9 +3869,15 @@ describe("ForgeService", () => {
|
||||
});
|
||||
for (const [headSha, expected] of [
|
||||
["old", 41],
|
||||
["other", 42],
|
||||
["other", undefined],
|
||||
] as const) {
|
||||
const runner = createScriptedRunner([JSON.stringify(older), JSON.stringify([older, newer])]);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(older),
|
||||
JSON.stringify([older, newer]),
|
||||
...(headSha === "old"
|
||||
? [directCommitsJson(["old"])]
|
||||
: [directCommitsJson(["old"]), directCommitsJson(["new"])]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
@@ -3410,6 +3917,7 @@ describe("ForgeService", () => {
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(closedDraft),
|
||||
JSON.stringify([closedDraft, merged]),
|
||||
directCommitsJson(["exact"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3482,6 +3990,7 @@ describe("ForgeService", () => {
|
||||
parent: { owner: { login: "acme" }, name: "app" },
|
||||
}),
|
||||
"[]",
|
||||
directCommitsJson(["checkout-head"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3510,7 +4019,7 @@ describe("ForgeService", () => {
|
||||
for (const [state, headSha, updatedAt, expected] of [
|
||||
["OPEN", "other", "2026-07-16T12:00:00Z", 8],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 7],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 8],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", undefined],
|
||||
] as const) {
|
||||
const parent = {
|
||||
...local,
|
||||
@@ -3521,6 +4030,11 @@ describe("ForgeService", () => {
|
||||
headRefOid: headSha,
|
||||
updatedAt,
|
||||
};
|
||||
const commitResponses: string[] = [];
|
||||
if (state !== "OPEN") {
|
||||
commitResponses.push(directCommitsJson(["local-head"]));
|
||||
if (expected !== 7) commitResponses.push(directCommitsJson(["other"]));
|
||||
}
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(local),
|
||||
JSON.stringify({
|
||||
@@ -3530,6 +4044,7 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
JSON.stringify([{ number: 8 }]),
|
||||
JSON.stringify(parent),
|
||||
...commitResponses,
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3626,6 +4141,8 @@ describe("ForgeService", () => {
|
||||
stderr: "",
|
||||
};
|
||||
}
|
||||
if (args[0] === "api" && args[1] === "graphql")
|
||||
return { stdout: directCommitsJson([checkoutSha]), stderr: "" };
|
||||
if (args[0] === "api") {
|
||||
// Newest first, and the checkout is sitting on the oldest attempt.
|
||||
return {
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
isGitHubHost,
|
||||
@@ -633,6 +637,22 @@ query PullRequestTimeline($owner: String!, $name: String!, $number: Int!) {
|
||||
}
|
||||
}`;
|
||||
|
||||
const PullRequestCommitPageSchema = z.object({
|
||||
nodes: z.array(z.object({ commit: z.object({ oid: z.string() }) })),
|
||||
pageInfo: z
|
||||
.object({ hasPreviousPage: z.boolean(), startCursor: z.string().nullable() })
|
||||
.refine(
|
||||
(page) => !page.hasPreviousPage || !!page.startCursor,
|
||||
"A previous commit page requires a cursor",
|
||||
),
|
||||
});
|
||||
|
||||
type PullRequestMembership =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "partial"; commitOids: string[]; cursor: string }
|
||||
| { kind: "complete"; commitOids: string[] }
|
||||
| { kind: "failed"; error: unknown };
|
||||
|
||||
const BatchPollPrNodeSchema = z.object({
|
||||
number: z.number(),
|
||||
url: z.string().catch(""),
|
||||
@@ -1125,6 +1145,7 @@ interface GitHubBatchDistribution {
|
||||
}
|
||||
|
||||
interface ResolvedPullRequestCandidate {
|
||||
membership: PullRequestMembership;
|
||||
status: CurrentPullRequestStatus;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
@@ -1173,6 +1194,9 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
// Rollup nodes for merged/closed PRs keyed by repo#number@headOid: their
|
||||
// checks can no longer change, so each is fetched at most once per daemon run.
|
||||
const frozenPullRequestChecksCache = new Map<string, unknown[]>();
|
||||
const readCommits = createPullRequestCommitReader();
|
||||
const terminalCommitPages = new Map<string, PullRequestMembership>();
|
||||
const batchMembership = new WeakMap<BatchPollPrNode, PullRequestMembership>();
|
||||
const pollRepositoryRedirects = new Map<
|
||||
string,
|
||||
{ owner: string; name: string; headRepositoryOwner: string }
|
||||
@@ -1661,15 +1685,32 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return;
|
||||
}
|
||||
|
||||
const repositories = new Map<GitHubBatchPollEntry, BatchPollRepository>();
|
||||
for (const [index, entry] of addressedEntries.entries()) {
|
||||
const parsed = BatchPollRepositorySchema.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (parsed.success) repositories.set(entry, parsed.data);
|
||||
}
|
||||
const failedCommitEntries = await loadBatchCommitPages(addressedEntries, repositories);
|
||||
const distribution = distributeGitHubPollBatch({
|
||||
entries: addressedEntries,
|
||||
aliases: response.aliases,
|
||||
repositories,
|
||||
args,
|
||||
startedAt,
|
||||
failedCommitEntries,
|
||||
});
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) {
|
||||
const error = new Error(
|
||||
"GitHub GraphQL polling is paused; pull request checks could not be refreshed",
|
||||
);
|
||||
for (const item of distribution.pendingChecks) {
|
||||
updatePollTargetAfterError(item.entry.target, error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (distribution.pendingChecks.length > 0) {
|
||||
await loadBatchPullRequestChecks(distribution.pendingChecks, startedAt);
|
||||
}
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) return;
|
||||
await Promise.all(distribution.legacyFallback.map((target) => runGitHubPoll(target)));
|
||||
if (distribution.redirected.length > 0) {
|
||||
await runGitHubPollBatch(distribution.redirected, startedAt);
|
||||
@@ -1680,6 +1721,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
entries: GitHubBatchPollEntry[];
|
||||
firstEntry: GitHubBatchPollEntry;
|
||||
args: string[];
|
||||
onError?: (entries: GitHubBatchPollEntry[], error: unknown) => void;
|
||||
}): Promise<GitHubBatchQueryResponse | null> {
|
||||
try {
|
||||
const stdout = await run(input.args, { cwd: input.firstEntry.target.cwd });
|
||||
@@ -1688,7 +1730,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
const isPaused = await pauseGitHubPollsAfterRateLimit(input.firstEntry, error);
|
||||
const partial = extractGraphqlBatchAliasesFromError(error);
|
||||
if (isPaused || !partial) {
|
||||
reportGitHubBatchError(input.entries, error);
|
||||
(input.onError ?? reportGitHubBatchError)(input.entries, error);
|
||||
return null;
|
||||
}
|
||||
const stdout = error instanceof GitHubCommandError ? (error.stdout ?? "") : "";
|
||||
@@ -1702,21 +1744,145 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
}
|
||||
}
|
||||
|
||||
function collectBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> = [];
|
||||
for (const entry of entries) {
|
||||
const repository = repositories.get(entry);
|
||||
if (!repository || (repository.isFork && repository.parent)) continue;
|
||||
const nodes = batchPollNodesForWorkspace(entry, repository);
|
||||
if (nodes.some((node) => node.state === "OPEN")) continue;
|
||||
for (const node of nodes) {
|
||||
batchMembership.set(
|
||||
node,
|
||||
terminalCommitPages.get(batchCommitKey(entry, node)) ?? { kind: "unknown" },
|
||||
);
|
||||
if (entry.target.headSha) candidates.push({ entry, node });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function batchCommitKey(entry: GitHubBatchPollEntry, node: BatchPollPrNode): string {
|
||||
return `${entry.host}/${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`;
|
||||
}
|
||||
|
||||
async function loadBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Promise<Set<GitHubBatchPollEntry>> {
|
||||
const pending = collectBatchCommitPages(entries, repositories);
|
||||
while (pending.length) {
|
||||
const blocked = new Set<GitHubBatchPollEntry>();
|
||||
const needing = unresolvedBatchCommitPages(pending).filter(({ entry, node }) => {
|
||||
if (batchMembership.get(node)?.kind === "failed") blocked.add(entry);
|
||||
return !blocked.has(entry);
|
||||
});
|
||||
if (!needing.length) break;
|
||||
const fields = needing.map(({ entry, node }, index) => {
|
||||
const membership = batchMembership.get(node);
|
||||
const cursor = membership?.kind === "partial" ? membership.cursor : null;
|
||||
return `${batchAlias(index)}: repository(owner: ${graphqlString(entry.owner)}, name: ${graphqlString(entry.name)}) { pullRequest(number: ${node.number}) { commits(last:100${cursor ? `, before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } }`;
|
||||
});
|
||||
const args = [
|
||||
"api",
|
||||
"graphql",
|
||||
"-f",
|
||||
`query=query PaseoBatchCommitPages { rateLimit { limit remaining resetAt } ${fields.join("\n")} }`,
|
||||
];
|
||||
const needingEntries = [...new Set(needing.map(({ entry }) => entry))];
|
||||
const response = await loadGitHubPollBatchResponse({
|
||||
entries: needingEntries,
|
||||
firstEntry: needingEntries[0]!,
|
||||
args,
|
||||
onError: (affected, error) => {
|
||||
for (const { entry, node } of needing)
|
||||
if (affected.includes(entry)) batchMembership.set(node, { kind: "failed", error });
|
||||
},
|
||||
});
|
||||
if (!response) break;
|
||||
const rateLimit = parseGraphqlBatchRateLimit(response.stdout);
|
||||
if (rateLimit && pauseGitHubPollsAtReserve(entries[0]!.host, rateLimit)) {
|
||||
const error = new GitHubGraphqlPollPausedError(rateLimit);
|
||||
for (const { node } of needing) batchMembership.set(node, { kind: "failed", error });
|
||||
break;
|
||||
}
|
||||
for (const [index, { entry, node }] of needing.entries()) {
|
||||
const parsed = z
|
||||
.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
})
|
||||
.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (!parsed.success) {
|
||||
batchMembership.set(node, { kind: "failed", error: parsed.error });
|
||||
continue;
|
||||
}
|
||||
const page = parsed.data.pullRequest.commits;
|
||||
const previous = batchMembership.get(node);
|
||||
const commitOids = [
|
||||
...(previous?.kind === "partial" ? previous.commitOids : []),
|
||||
...page.nodes.map(({ commit }) => commit.oid),
|
||||
];
|
||||
const membership: PullRequestMembership =
|
||||
page.pageInfo.hasPreviousPage && page.pageInfo.startCursor
|
||||
? { kind: "partial", commitOids, cursor: page.pageInfo.startCursor }
|
||||
: { kind: "complete", commitOids };
|
||||
batchMembership.set(node, membership);
|
||||
const key = batchCommitKey(entry, node);
|
||||
terminalCommitPages.delete(key);
|
||||
terminalCommitPages.set(key, membership);
|
||||
if (terminalCommitPages.size > 512)
|
||||
terminalCommitPages.delete(terminalCommitPages.keys().next().value!);
|
||||
}
|
||||
}
|
||||
return reportUnresolvedCommitReads(pending);
|
||||
}
|
||||
|
||||
function unresolvedBatchCommitPages(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const byEntry = new Map<GitHubBatchPollEntry, BatchPollPrNode[]>();
|
||||
for (const { entry, node } of candidates) {
|
||||
const nodes = byEntry.get(entry) ?? [];
|
||||
nodes.push(node);
|
||||
byEntry.set(entry, nodes);
|
||||
}
|
||||
return [...byEntry].flatMap(([entry, nodes]) =>
|
||||
inspectBatchPollCandidates(entry, nodes).pending.map((node) => ({ entry, node })),
|
||||
);
|
||||
}
|
||||
|
||||
function reportUnresolvedCommitReads(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Set<GitHubBatchPollEntry> {
|
||||
const failed = new Set<GitHubBatchPollEntry>();
|
||||
for (const { entry, node } of unresolvedBatchCommitPages(candidates)) {
|
||||
const membership = batchMembership.get(node);
|
||||
if (membership?.kind !== "failed" || failed.has(entry)) continue;
|
||||
failed.add(entry);
|
||||
updatePollTargetAfterError(entry.target, membership.error);
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
function distributeGitHubPollBatch(input: {
|
||||
entries: GitHubBatchPollEntry[];
|
||||
aliases: Record<string, unknown>;
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>;
|
||||
args: string[];
|
||||
startedAt: number;
|
||||
failedCommitEntries: ReadonlySet<GitHubBatchPollEntry>;
|
||||
}): GitHubBatchDistribution {
|
||||
const distribution: GitHubBatchDistribution = {
|
||||
pendingChecks: [],
|
||||
legacyFallback: [],
|
||||
redirected: [],
|
||||
};
|
||||
for (const [index, entry] of input.entries.entries()) {
|
||||
const aliasValue = input.aliases[batchAlias(index)];
|
||||
const repository = aliasValue ? BatchPollRepositorySchema.safeParse(aliasValue) : null;
|
||||
if (!repository?.success) {
|
||||
for (const entry of input.entries) {
|
||||
if (input.failedCommitEntries.has(entry)) continue;
|
||||
const repository = input.repositories.get(entry);
|
||||
if (!repository) {
|
||||
updatePollTargetAfterError(
|
||||
entry.target,
|
||||
new GitHubCommandError({
|
||||
@@ -1728,32 +1894,29 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (repository.data.isFork && repository.data.parent) {
|
||||
const forkOwner = repository.data.owner?.login ?? entry.owner;
|
||||
if (repository.isFork && repository.parent) {
|
||||
const forkOwner = repository.owner?.login ?? entry.owner;
|
||||
pollRepositoryRedirects.set(batchRepositoryRedirectKey(entry), {
|
||||
owner: repository.data.parent.owner.login,
|
||||
name: repository.data.parent.name,
|
||||
owner: repository.parent.owner.login,
|
||||
name: repository.parent.name,
|
||||
headRepositoryOwner: forkOwner,
|
||||
});
|
||||
distribution.redirected.push(entry);
|
||||
continue;
|
||||
}
|
||||
const node = selectBatchPollNode(entry, repository.data);
|
||||
const node = selectBatchPollNode(entry, repository);
|
||||
if (!node) {
|
||||
// Legacy fallback covers the two ways "no match" can be wrong: a fork
|
||||
// whose PR lives in the parent repository, and a full candidate page —
|
||||
// ten newer same-named fork PRs can crowd the checkout's own PR out of
|
||||
// the first:N window, so absence is only conclusive on a partial page.
|
||||
if (
|
||||
repository.data.isFork ||
|
||||
repository.data.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT
|
||||
) {
|
||||
if (repository.isFork || repository.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT) {
|
||||
distribution.legacyFallback.push(entry.target);
|
||||
} else {
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node: null,
|
||||
repository: repository.data,
|
||||
repository: repository,
|
||||
rollup: null,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1770,7 +1933,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node,
|
||||
repository: repository.data,
|
||||
repository: repository,
|
||||
rollup: cachedRollup,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1778,7 +1941,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
distribution.pendingChecks.push({
|
||||
entry,
|
||||
node,
|
||||
repository: repository.data,
|
||||
repository: repository,
|
||||
cacheKey: frozenKey,
|
||||
});
|
||||
}
|
||||
@@ -1802,41 +1965,59 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return `${entry.host}\n${entry.originOwner}/${entry.originName}`;
|
||||
}
|
||||
|
||||
function batchPollNodesForWorkspace(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode[] {
|
||||
// Branch names also match other forks; reject those before loading commit lists.
|
||||
const owner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
return repository.pullRequests.nodes.filter(
|
||||
(node) =>
|
||||
node.headRefName === entry.target.headRef &&
|
||||
(owner
|
||||
? node.headRepositoryOwner?.login === owner
|
||||
: node.headRepositoryOwner?.login?.toLowerCase() === selfOwner),
|
||||
);
|
||||
}
|
||||
|
||||
function selectBatchPollNode(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode | null {
|
||||
// Prefer the canonical owner from the response: the origin slug can carry
|
||||
// stale casing or a pre-transfer owner that repository() redirects from.
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
const headRepositoryOwner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const resolution = inspectBatchPollCandidates(
|
||||
entry,
|
||||
batchPollNodesForWorkspace(entry, repository),
|
||||
);
|
||||
return resolution.pending.length ? null : resolution.match;
|
||||
}
|
||||
|
||||
function inspectBatchPollCandidates(
|
||||
entry: GitHubBatchPollEntry,
|
||||
nodes: BatchPollPrNode[],
|
||||
): { match: BatchPollPrNode | null; pending: BatchPollPrNode[] } {
|
||||
const nodeByCandidate = new Map<ResolvedPullRequestCandidate, BatchPollPrNode>();
|
||||
const candidates: ResolvedPullRequestCandidate[] = [];
|
||||
for (const node of repository.pullRequests.nodes) {
|
||||
for (const node of nodes) {
|
||||
const candidate = toCurrentPullRequestCandidate(
|
||||
toBatchCurrentPullRequestItem(node, undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
// pullRequests(headRefName:) also matches forks whose branch shares the
|
||||
// name. Without a fork-owner hint the workspace branch lives in this
|
||||
// repository, so only self-owned heads are real candidates (mirrors
|
||||
// `gh pr view` resolving the current branch's own PR).
|
||||
if (!headRepositoryOwner && candidate.headRepositoryOwner?.toLowerCase() !== selfOwner) {
|
||||
continue;
|
||||
}
|
||||
if (!candidate) continue;
|
||||
candidate.membership = batchMembership.get(node) ?? { kind: "unknown" };
|
||||
nodeByCandidate.set(candidate, node);
|
||||
candidates.push(candidate);
|
||||
}
|
||||
const match = pickPullRequestCandidate({
|
||||
const resolution = inspectPullRequestCandidates({
|
||||
candidates,
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner ?? entry.headRepositoryOwner,
|
||||
});
|
||||
return match ? (nodeByCandidate.get(match) ?? null) : null;
|
||||
return {
|
||||
match: resolution.match ? nodeByCandidate.get(resolution.match)! : null,
|
||||
pending: resolution.pending.map((candidate) => nodeByCandidate.get(candidate)!),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadBatchPullRequestChecks(
|
||||
@@ -1961,7 +2142,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
toBatchCurrentPullRequestItem(node, input.rollup ?? undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
|
||||
const membership = batchMembership.get(node);
|
||||
const commitOids =
|
||||
membership?.kind === "complete" || membership?.kind === "partial"
|
||||
? membership.commitOids
|
||||
: undefined;
|
||||
status = built
|
||||
? { ...built, commitOids, forgeSpecific: { forge: "github", ...facts } }
|
||||
: null;
|
||||
}
|
||||
const cacheKey = buildCacheKey({
|
||||
cwd: entry.target.cwd,
|
||||
@@ -2177,6 +2365,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
readOptions: input,
|
||||
load: async () => {
|
||||
const status = await resolveCurrentPullRequestView({
|
||||
readCommits,
|
||||
cwd: input.cwd,
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
@@ -2989,20 +3178,13 @@ async function resolveCurrentPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const viewCandidate = await tryCurrentPullRequestView(options);
|
||||
const viewMatch = viewCandidate
|
||||
? pickPullRequestCandidate({
|
||||
candidates: [viewCandidate],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.headRepositoryOwner,
|
||||
})
|
||||
: null;
|
||||
if (viewMatch?.status.state === "open") {
|
||||
return viewMatch.status;
|
||||
}
|
||||
const viewCandidates = viewCandidate ? [viewCandidate] : [];
|
||||
const open = pickPullRequestCandidate({ ...options, candidates: viewCandidates });
|
||||
if (open?.status.state === "open") return open.status;
|
||||
|
||||
let headRepositoryOwner = options.headRepositoryOwner;
|
||||
|
||||
@@ -3012,13 +3194,17 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const parentOwner = repo?.parent?.owner?.login;
|
||||
const parentName = repo?.parent?.name;
|
||||
if (!forkOwner) {
|
||||
return viewMatch?.status ?? null;
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
...options,
|
||||
candidates: viewCandidates,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
}
|
||||
if (parentOwner && parentName) {
|
||||
return resolveForkPullRequestView({
|
||||
...options,
|
||||
forkOwner,
|
||||
viewMatch,
|
||||
viewCandidate,
|
||||
repo: `${parentOwner}/${parentName}`,
|
||||
});
|
||||
}
|
||||
@@ -3028,10 +3214,14 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const candidates = await listCurrentPullRequestCandidates({
|
||||
cwd: options.cwd,
|
||||
headRef: options.headRef,
|
||||
headRepositoryOwner,
|
||||
run: options.run,
|
||||
});
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates: viewMatch ? [...candidates, viewMatch] : candidates,
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
candidates: [...candidates, ...viewCandidates],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner,
|
||||
@@ -3052,8 +3242,9 @@ async function resolveForkPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
forkOwner: string;
|
||||
viewMatch: ResolvedPullRequestCandidate | null;
|
||||
viewCandidate: ResolvedPullRequestCandidate | null;
|
||||
repo: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const numbers = await listForkPullRequestNumbers(options);
|
||||
@@ -3067,16 +3258,20 @@ async function resolveForkPullRequestView(options: {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const match = pickPullRequestCandidate({
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
candidates: [
|
||||
...candidates.filter(
|
||||
(candidate): candidate is ResolvedPullRequestCandidate =>
|
||||
candidate !== null && candidate.headRepositoryOwner === options.forkOwner,
|
||||
),
|
||||
...(options.viewMatch ? [options.viewMatch] : []),
|
||||
...(options.viewCandidate ? [options.viewCandidate] : []),
|
||||
],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.forkOwner,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
}
|
||||
@@ -3170,6 +3365,62 @@ async function loadPullRequestGithubFacts(options: {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAndPickPullRequestCandidate(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0] & {
|
||||
cwd: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<ResolvedPullRequestCandidate | null> {
|
||||
for (;;) {
|
||||
const resolution = inspectPullRequestCandidates(options);
|
||||
const next = resolution.pending[0];
|
||||
if (!next) return resolution.match;
|
||||
await completeCandidateCommits(next, options);
|
||||
}
|
||||
}
|
||||
|
||||
async function completeCandidateCommits(
|
||||
candidate: ResolvedPullRequestCandidate,
|
||||
options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<void> {
|
||||
const status = candidate.status;
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) return;
|
||||
if (options.headRepositoryOwner && candidate.headRepositoryOwner !== options.headRepositoryOwner)
|
||||
return;
|
||||
if (status.state === "open" || candidate.membership.kind === "complete") return;
|
||||
const commitOids = await options.readCommits(`${status.url}@${status.headSha}`, async () => {
|
||||
const commits: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
for (;;) {
|
||||
const query = `query { repository(owner:${graphqlString(status.repoOwner!)},name:${graphqlString(status.repoName!)}) { pullRequest(number:${status.number}) { commits(last:100${cursor ? `,before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } } }`;
|
||||
const stdout = await options.run(["api", "graphql", "-f", `query=${query}`], {
|
||||
cwd: options.cwd,
|
||||
});
|
||||
const page = z
|
||||
.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(JSON.parse(stdout)).data.repository.pullRequest.commits;
|
||||
commits.push(...page.nodes.map(({ commit }) => commit.oid));
|
||||
if (!page.pageInfo?.hasPreviousPage) return commits;
|
||||
cursor = page.pageInfo.startCursor;
|
||||
}
|
||||
});
|
||||
candidate.membership = { kind: "complete", commitOids };
|
||||
status.commitOids = commitOids;
|
||||
}
|
||||
|
||||
async function tryCurrentPullRequestView(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
@@ -3183,10 +3434,11 @@ async function tryCurrentPullRequestView(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
return parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
const candidate = parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidate;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return null;
|
||||
@@ -3198,6 +3450,7 @@ async function tryCurrentPullRequestView(options: {
|
||||
async function listCurrentPullRequestCandidates(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<ResolvedPullRequestCandidate[]> {
|
||||
const args = ["pr", "list", "--state", "all", "--head", options.headRef, "--limit", "10"];
|
||||
@@ -3207,10 +3460,11 @@ async function listCurrentPullRequestCandidates(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
return parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
const candidates = parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidates;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return [];
|
||||
@@ -3428,6 +3682,7 @@ function toCurrentPullRequestCandidate(
|
||||
const headSha = item.headRefOid;
|
||||
return {
|
||||
status,
|
||||
membership: { kind: "unknown" },
|
||||
updatedAt: item.updatedAt,
|
||||
...(headSha ? { headSha } : {}),
|
||||
...(headRepositoryOwner ? { headRepositoryOwner } : {}),
|
||||
@@ -3448,6 +3703,38 @@ function pickPullRequestCandidate(options: {
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}): ResolvedPullRequestCandidate | null {
|
||||
const result = inspectPullRequestCandidates(options);
|
||||
return result.pending.length ? null : result.match;
|
||||
}
|
||||
|
||||
function inspectPullRequestCandidates(options: Parameters<typeof pickPullRequestCandidate>[0]): {
|
||||
match: ResolvedPullRequestCandidate | null;
|
||||
pending: ResolvedPullRequestCandidate[];
|
||||
} {
|
||||
const matching = matchingPullRequestCandidates(options);
|
||||
const open = matching.find((candidate) => candidate.status.state === "open");
|
||||
if (open) return { match: open, pending: [] };
|
||||
const pending: ResolvedPullRequestCandidate[] = [];
|
||||
if (!options.headSha) return { match: null, pending };
|
||||
for (const candidate of matching) {
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: options.headSha,
|
||||
pullRequestCommits:
|
||||
candidate.membership.kind === "complete" || candidate.membership.kind === "partial"
|
||||
? candidate.membership.commitOids
|
||||
: undefined,
|
||||
})
|
||||
)
|
||||
return { match: candidate, pending };
|
||||
if (candidate.membership.kind !== "complete") pending.push(candidate);
|
||||
}
|
||||
return { match: null, pending };
|
||||
}
|
||||
|
||||
function matchingPullRequestCandidates(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0],
|
||||
): ResolvedPullRequestCandidate[] {
|
||||
const matching = options.candidates.filter((candidate) => {
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) {
|
||||
return false;
|
||||
@@ -3460,7 +3747,7 @@ function pickPullRequestCandidate(options: {
|
||||
matching.sort((left, right) =>
|
||||
comparePullRequestCandidatePreference(left, right, options.headSha),
|
||||
);
|
||||
return matching[0] ?? null;
|
||||
return matching;
|
||||
}
|
||||
|
||||
function comparePullRequestCandidatePreference(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus } from "./forge-service.js";
|
||||
@@ -375,6 +377,7 @@ describe("createGitLabService", () => {
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newestStale, exactOlder]));
|
||||
if (args[1] === "view" && args[2] === "270") return ok(JSON.stringify(exactOlder));
|
||||
if (args[1]?.includes("/commits?")) return ok(JSON.stringify([{ id: checkoutSha }]));
|
||||
if (args[0] === "api") return ok("{}");
|
||||
throw new Error(`unexpected call: ${args.join(" ")}`);
|
||||
});
|
||||
@@ -386,25 +389,93 @@ describe("createGitLabService", () => {
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(270);
|
||||
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
expect(calls[2]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("checks fork MR membership on a reused base branch and caches successful lists", async () => {
|
||||
const requests = Array.from({ length: 100 }, (_, index) => ({
|
||||
...OPEN_MR,
|
||||
iid: index + 1,
|
||||
source_branch: "main",
|
||||
state: "closed",
|
||||
source_project_id: 202,
|
||||
target_project_id: 101,
|
||||
sha: `fork-head-${index}`,
|
||||
web_url: `https://gitlab.example.com/example-group/example-project/-/merge_requests/${index + 1}`,
|
||||
}));
|
||||
let commitReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify(requests));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
commitReads++;
|
||||
return ok(JSON.stringify([{ id: "fork-own-commit" }]));
|
||||
}
|
||||
if (args[1] === "view") return ok(JSON.stringify(requests[0]));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: "main", headSha: "inherited-base" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true }),
|
||||
).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, headSha: "fork-own-commit", force: true }),
|
||||
).resolves.toMatchObject({ number: 1, state: "closed" });
|
||||
expect(commitReads).toBe(100);
|
||||
});
|
||||
|
||||
it("rejects an unknown newer MR instead of choosing an older match and retries", async () => {
|
||||
const older = { ...OPEN_MR, iid: 270, state: "merged", sha: "older-head" };
|
||||
const newer = { ...older, iid: 271, state: "closed", sha: "newer-head" };
|
||||
let failedReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newer, older]));
|
||||
if (args[1]?.includes("/271/commits?")) {
|
||||
failedReads++;
|
||||
if (failedReads < 3) throw new Error("HTTP 502");
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
}
|
||||
if (args[1]?.includes("/270/commits?"))
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
if (args[1] === "view") return ok(JSON.stringify(newer));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: OPEN_MR.source_branch, headSha: "workspace-commit" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).rejects.toThrow(
|
||||
"GitLab CLI command failed",
|
||||
);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "retry" }),
|
||||
).rejects.toThrow("GitLab CLI command failed");
|
||||
expect(failedReads).toBe(2);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "recovered" }),
|
||||
).resolves.toMatchObject({ number: 271 });
|
||||
});
|
||||
|
||||
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = {
|
||||
...OPEN_MR,
|
||||
state: "merged",
|
||||
source_branch: "dev",
|
||||
sha: "1111111111111111111111111111111111111111",
|
||||
sha: pullRequestCommit,
|
||||
};
|
||||
const { service, calls } = makeService((args) =>
|
||||
ok(JSON.stringify(args[1] === "list" ? [stale] : stale)),
|
||||
);
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify([{ id: workspaceCommit }, { id: pullRequestCommit }]));
|
||||
return ok(JSON.stringify(args[1] === "list" ? [stale] : stale));
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
cwd,
|
||||
headRef: "dev",
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
headSha: workspaceCommit,
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(calls[0]).toEqual(currentMrListArgs("dev"));
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import { findExecutable } from "../executable-resolution/executable-resolution.js";
|
||||
@@ -153,6 +157,7 @@ const GitLabMergeRequestSchema = z
|
||||
source_branch: z.string(),
|
||||
target_branch: z.string(),
|
||||
sha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
source_project_id: z.number().nullable().optional(),
|
||||
target_project_id: z.number().nullable().optional(),
|
||||
draft: z.boolean().optional(),
|
||||
@@ -739,6 +744,7 @@ function toCurrentPullRequestStatus(
|
||||
baseRefName: mr.target_branch,
|
||||
headRefName: mr.source_branch,
|
||||
...(mr.sha ? { headSha: mr.sha } : {}),
|
||||
commitOids: mr.commitOids,
|
||||
isMerged: mr.state === "merged" || mr.merged_at != null,
|
||||
isDraft: mr.draft ?? mr.work_in_progress ?? false,
|
||||
mergeable: mapMergeable(mr),
|
||||
@@ -919,6 +925,7 @@ function gitLabNumberQuery(query: string | undefined): string | null {
|
||||
}
|
||||
|
||||
export function createGitLabService(options: CreateGitLabServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runGlabCommand;
|
||||
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -992,15 +999,32 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
): Promise<GitLabMergeRequest | null> {
|
||||
const mergeRequests = await listMergeRequestsBySourceBranch(cwd, headRef);
|
||||
const candidates = mergeRequests.filter((mr) => mr.source_branch === headRef);
|
||||
const match =
|
||||
candidates.find((mr) => mapMergeRequestState(mr.state) === "open") ??
|
||||
candidates.find(
|
||||
(mr) =>
|
||||
mapMergeRequestState(mr.state) !== "open" && headSha !== undefined && mr.sha === headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? viewMergeRequest(cwd, String(match.iid)) : null;
|
||||
const open = candidates.find((candidate) => mapMergeRequestState(candidate.state) === "open");
|
||||
if (open) return viewMergeRequest(cwd, String(open.iid));
|
||||
candidates.sort((left, right) => Number(right.sha === headSha) - Number(left.sha === headSha));
|
||||
for (const mr of candidates) {
|
||||
const project = mr.target_project_id ?? extractProjectPath(mr.references?.full);
|
||||
if (project === undefined) continue;
|
||||
const commitOids = await readRequestCommits(`${mr.web_url}@${mr.sha}`, async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const commits = await runJson(
|
||||
[
|
||||
"api",
|
||||
`projects/${encodeURIComponent(project)}/merge_requests/${mr.iid}/commits?per_page=100&page=${page}`,
|
||||
],
|
||||
{ cwd },
|
||||
z.array(z.object({ id: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.id));
|
||||
if (commits.length < 100) return result;
|
||||
}
|
||||
});
|
||||
if (pullRequestContainsCommit({ workspaceCommit: headSha, pullRequestCommits: commitOids })) {
|
||||
return { ...(await viewMergeRequest(cwd, String(mr.iid))), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/** Only commits introduced by the request establish workspace ownership. */
|
||||
export function pullRequestContainsCommit(input: {
|
||||
workspaceCommit?: string;
|
||||
pullRequestCommits?: readonly string[];
|
||||
}): boolean {
|
||||
return !!input.workspaceCommit && !!input.pullRequestCommits?.includes(input.workspaceCommit);
|
||||
}
|
||||
|
||||
/** Terminal commit lists are immutable for a request head. Failed reads remain retryable. */
|
||||
export function createPullRequestCommitReader() {
|
||||
const cache = new Map<string, Promise<string[]>>();
|
||||
return (key: string, load: () => Promise<string[]>): Promise<string[]> => {
|
||||
const existing = cache.get(key);
|
||||
if (existing) return existing;
|
||||
const commits = load().catch((error: unknown) => {
|
||||
cache.delete(key);
|
||||
throw error;
|
||||
});
|
||||
cache.set(key, commits);
|
||||
if (cache.size > 1024) cache.delete(cache.keys().next().value!);
|
||||
return commits;
|
||||
};
|
||||
}
|
||||
@@ -355,13 +355,22 @@ it.each(["detach", "closeTerminals"] as const)(
|
||||
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
|
||||
});
|
||||
const [record] = await workerRecords(paseoHome);
|
||||
process.kill(record!.pid, "SIGKILL");
|
||||
await manager[operation]();
|
||||
await expect(
|
||||
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
|
||||
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
|
||||
await manager.closeTerminals();
|
||||
expect(await workerRecords(paseoHome)).toEqual([]);
|
||||
const programPid = record!.terminals[0]!.pid;
|
||||
try {
|
||||
process.kill(record!.pid, "SIGKILL");
|
||||
await manager[operation]();
|
||||
await expect(
|
||||
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
|
||||
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
|
||||
await manager.closeTerminals();
|
||||
expect(await workerRecords(paseoHome)).toEqual([]);
|
||||
} finally {
|
||||
// A hard-crashed Windows worker can leave its terminal program alive.
|
||||
// The test owns that program even after the manager retires its record.
|
||||
if (isProcessAlive(programPid)) process.kill(programPid, "SIGKILL");
|
||||
await waitForCondition(() => !isProcessAlive(programPid), 5000);
|
||||
await waitForCondition(() => !isProcessAlive(record!.pid), 5000);
|
||||
}
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
|
||||
export function createPullRequestHistory() {
|
||||
const root = resolve(import.meta.dirname, "../../../../.artifacts");
|
||||
mkdirSync(root, { recursive: true });
|
||||
const directory = mkdtempSync(join(root, "pr-history-"));
|
||||
const remote = join(directory, "remote");
|
||||
const cwd = join(directory, "checkout");
|
||||
const git = (path: string, args: string[]) =>
|
||||
execFileSync("git", args, {
|
||||
cwd: path,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
}).trim();
|
||||
git(directory, ["init", remote]);
|
||||
const commit = (message: string) =>
|
||||
git(remote, [
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
message,
|
||||
]);
|
||||
commit("workspace");
|
||||
const workspaceCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
git(directory, ["clone", remote, cwd]);
|
||||
commit("remote branch update");
|
||||
const pullRequestCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
return {
|
||||
cwd,
|
||||
remote,
|
||||
workspaceCommit,
|
||||
pullRequestCommit,
|
||||
git: (args: string[]) => git(cwd, args),
|
||||
dispose: () => rmSync(directory, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user