Hide historical PR badges on the default branch (#10053)

Hide closed and merged requests on the origin repository’s default branch. Keep branch-based status matching for feature workspaces.

Closes #9908.
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-18 11:08:44 +07:00
1 parent 63a33ac3fd
commit 91e7293773
11 files changed
+379 -149

No files matched your search

+4 -2
View File
@@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with:
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
HEAD, then the most recently updated terminal request. When the forge identifies
the checkout's branch as the origin repository's default branch, only open
requests are eligible. A reused feature 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.
@@ -604,6 +604,7 @@ interface WorkspaceGitAuxiliaryReadCacheEntry<T> {
interface WorkspaceForgePrStatusPollTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -3150,11 +3151,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (resolution.service.retainCurrentPullRequestStatusPoll) {
target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({
cwd: target.cwd,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
...pollTarget,
onStatus: (status) => {
if (!this.isActiveObservedWorkspaceTarget(target)) {
return;
@@ -3226,11 +3223,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
try {
const status = await service.getCurrentPullRequestStatus({
cwd: target.cwd,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
...pollTarget,
reason: "self-heal-forge-pr-status",
});
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
@@ -3285,13 +3278,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch
? target.latestFacts.pullRequestLookupTarget
: null;
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
return lookupTarget;
}
if (lookupTarget) {
return lookupTarget;
return git.currentBranch === lookupTarget.headRef
? lookupTarget
: { ...lookupTarget, currentBranch: git.currentBranch };
}
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
return null;
}
return { headRef: git.currentBranch };
}
@@ -4424,6 +4418,7 @@ function buildWorkspaceForgePrStatusPollKey({
forge,
remoteUrl,
target.headRef,
target.currentBranch ?? null,
target.headSha ?? null,
target.headRepositoryOwner ?? null,
]);
+23 -14
View File
@@ -436,6 +436,22 @@ export interface CreatePullRequestOptions {
body?: string;
}
export interface CurrentPullRequestLookup {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
/** Local branch name when it differs from the PR source ref. */
currentBranch?: string;
}
export function isOnDefaultBranch(
lookup: Pick<CurrentPullRequestLookup, "currentBranch" | "headRef">,
defaultBranch: string | null | undefined,
): boolean {
return (lookup.currentBranch ?? lookup.headRef) === defaultBranch;
}
export interface ForgeService {
listPullRequests(options: ListPullRequestsOptions): Promise<PullRequestSummary[]>;
listIssues(options: ListIssuesOptions): Promise<IssueSummary[]>;
@@ -475,12 +491,7 @@ export interface ForgeService {
*/
getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise<string | null>;
getCurrentPullRequestStatus(
options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
} & ForgeReadOptions,
options: CurrentPullRequestLookup & ForgeReadOptions,
): Promise<CurrentPullRequestStatus | null>;
getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise<PullRequestTimeline>;
getCheckDetails(options: GetCheckDetailsOptions): Promise<CheckDetails>;
@@ -516,14 +527,12 @@ export interface ForgeService {
* cannot change the outcome and is pure overhead.
*/
authProbeCanThrow?: boolean;
retainCurrentPullRequestStatusPoll?(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
}): { unsubscribe: () => void };
retainCurrentPullRequestStatusPoll?(
options: CurrentPullRequestLookup & {
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
},
): { unsubscribe: () => void };
invalidate(options: { cwd: string }): void;
dispose?(): void;
}
@@ -2036,6 +2036,33 @@ describe("createGiteaService", () => {
]);
});
it("hides a historical PR on the repository's default branch", async () => {
const historical = currentPullRequestApi({
number: 8,
state: "closed",
headRef: "trunk",
headSha: "8888888888888888888888888888888888888888",
});
const { service } = makeService((args) => {
if (args[0] === "pr" && args[1] === "list") return ok("[]");
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
return ok(JSON.stringify([historical]));
}
if (args[0] === "api" && args[1] === "repos/example-user/sample-repo") {
return ok(
JSON.stringify({
full_name: "example-user/sample-repo",
default_branch: "trunk",
}),
);
}
throw new Error(`unexpected call: ${args.join(" ")}`);
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
).resolves.toBeNull();
});
it("falls back to the recent all-state PR window for a recently closed current branch PR", async () => {
const headSha = "8888888888888888888888888888888888888888";
const closedPr = currentPullRequestApi({
+28 -23
View File
@@ -26,11 +26,13 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
CheckDetails,
CreatePullRequestOptions,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -251,6 +253,7 @@ const GiteaPullRequestApiSchema = z
const GiteaRepositoryApiSchema = z
.object({
full_name: z.string(),
default_branch: z.string().nullish(),
parent: z.object({ full_name: z.string().optional() }).nullable().optional(),
})
.passthrough();
@@ -1585,11 +1588,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return { items, truncated: true };
}
async function loadCurrentPullRequestStatus(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<CurrentPullRequestStatus | null> {
async function loadCurrentPullRequestStatus(
input: CurrentPullRequestLookup,
): Promise<CurrentPullRequestStatus | null> {
const match = await findCurrentPullRequestForHeadRef(input);
if (!match) {
return null;
@@ -1613,11 +1614,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return identity ? { owner: identity.owner, name: identity.name } : null;
}
async function findCurrentPullRequestForHeadRef(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<GiteaPrListItem | null> {
function readRepository(cwd: string, repoPath: string) {
return runJson(["api", repoPath], { cwd }, GiteaRepositoryApiSchema);
}
function repositoryApiPath(repo: { owner: string; name: string } | null): string {
return repo
? `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`
: "repos/{owner}/{repo}";
}
async function findCurrentPullRequestForHeadRef(
input: CurrentPullRequestLookup,
): Promise<GiteaPrListItem | null> {
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
const expectedHeadOwner = repoIdentity?.owner ?? null;
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
@@ -1628,9 +1637,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// tea discovers repository context from any configured git remote, while
// the default remote resolver reads origin only. Preserve that broader
// discovery for repositories whose primary remote has another name.
const repoPath = repoIdentity
? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}`
: "repos/{owner}/{repo}";
const repoPath = repositoryApiPath(repoIdentity);
const recentItems = await runJsonArray(
[
"api",
@@ -1666,6 +1673,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
) ??
candidates[0] ??
null;
if (match && mapGiteaState(match.state) !== "open") {
const repository = await readRepository(input.cwd, repoPath).catch(() => null);
if (isOnDefaultBranch(input, repository?.default_branch)) {
return null;
}
}
return match ? currentPullRequestApiToListItem(match) : null;
}
@@ -2020,20 +2033,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
if (!repo) {
return null;
}
const repository = await runJson(
["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`],
{ cwd: input.cwd },
GiteaRepositoryApiSchema,
);
const repository = await readRepository(input.cwd, repositoryApiPath(repo));
return repository.parent?.full_name ?? null;
},
getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
return loadCurrentPullRequestStatus({
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
});
return loadCurrentPullRequestStatus(input);
},
async getPullRequest(input: GetPullRequestOptions): Promise<PullRequestSummary> {
@@ -552,7 +552,7 @@ describe("ForgeService", () => {
"view",
"fork-owner/repo",
"--json",
"owner,name,parent",
"owner,name,parent,defaultBranchRef",
]);
});
@@ -862,7 +862,7 @@ describe("ForgeService", () => {
expect(runner.calls).toHaveLength(2);
expect(runner.calls[0]).toEqual({
cwd: "/repo",
args: ["repo", "view", "--json", "owner,name,parent"],
args: ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
});
expect(runner.calls[1]?.cwd).toBe("/repo");
expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]);
@@ -1111,6 +1111,56 @@ describe("ForgeService", () => {
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
});
it.each([
{ currentBranch: undefined, state: "MERGED", expected: null, calls: 1 },
{ currentBranch: undefined, state: "OPEN", expected: "open", calls: 2 },
{ currentBranch: "fork/trunk", state: "MERGED", expected: "merged", calls: 2 },
])(
"polls a $state PR with source trunk from checkout $currentBranch",
async ({ currentBranch, state, expected, calls }) => {
const runner = createScriptedRunner([
batchPollStatusJson({
t0: batchPollRepositoryJson(
[
batchPollPrNodeJson({
headRefName: "trunk",
state,
...(state === "OPEN" ? { mergedAt: null } : {}),
}),
],
{
defaultBranchRef: { name: "trunk" },
},
),
}),
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => "acme/widgets",
now: () => 0,
});
const statuses: Array<CurrentPullRequestStatus | null> = [];
try {
service.retainCurrentPullRequestStatusPoll?.({
cwd: "/repo",
headRef: "trunk",
currentBranch,
onStatus: (status) => statuses.push(status),
});
await vi.advanceTimersByTimeAsync(0);
await flushMicrotasks();
expect(statuses.map((status) => status?.state ?? null)).toEqual([expected]);
expect(runner.calls).toHaveLength(calls);
} finally {
service.dispose?.();
}
},
);
it("batches PR status polls across workspaces into one GraphQL request", async () => {
let now = 0;
const runner = createScriptedRunner([
@@ -1490,13 +1540,19 @@ describe("ForgeService", () => {
batchPollStatusJson({
t0: batchPollRepositoryJson([], { isFork: true, parent }),
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
]),
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
]);
const service = createGitHubService({
ttlMs: 0,
@@ -1524,6 +1580,9 @@ describe("ForgeService", () => {
expect(runner.calls[1]?.args[3]).toContain(
't0: repository(owner: "upstream", name: "widgets")',
);
expect(runner.calls[1]?.args[3]).toContain(
'origin0: repository(owner: "forkowner", name: "widgets")',
);
expect(statuses).toEqual([
expect.objectContaining({ number: 42, repoOwner: "upstream", checksStatus: "success" }),
]);
@@ -3278,6 +3337,30 @@ describe("ForgeService", () => {
});
});
it.each([
["main", "CLOSED"],
["master", "MERGED"],
])("hides a %s PR on the default branch in a direct read (state %s)", async (headRef, state) => {
const historical = currentPullRequestJson({
headRefName: headRef,
headRepositoryOwner: { login: "acme" },
state,
});
const runner = createScriptedRunner([
historical,
JSON.stringify({ owner: { login: "acme" }, defaultBranchRef: { name: headRef } }),
JSON.stringify([JSON.parse(historical)]),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef }),
).resolves.toBeNull();
});
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
const headSha = "2222222222222222222222222222222222222222";
const runner = createRunner([
@@ -3605,7 +3688,7 @@ describe("ForgeService", () => {
});
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
["pr", "view", "41", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
@@ -3837,7 +3920,7 @@ describe("ForgeService", () => {
});
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
[
@@ -3902,7 +3985,7 @@ describe("ForgeService", () => {
).resolves.toBeNull();
expect(calls.map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
[
"pr",
"list",
@@ -4750,7 +4833,12 @@ describe("ForgeService", () => {
}),
).resolves.toEqual({ url: "https://github.com/acme/repo/pull/7", number: 7 });
expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]);
expect(runner.calls[0]?.args).toEqual([
"repo",
"view",
"--json",
"owner,name,parent,defaultBranchRef",
]);
expect(runner.calls[1]?.args).toEqual([
"api",
"-X",
@@ -4824,7 +4912,7 @@ describe("ForgeService", () => {
expect(readFakeGitHubCliLog(fixture.logPath)).toEqual(
expect.arrayContaining([
"auth status --hostname github.acme.internal|",
"repo view --json owner,name,parent|github.acme.internal",
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
@@ -4869,7 +4957,7 @@ describe("ForgeService", () => {
).toHaveLength(2);
expect(log).toEqual(
expect.arrayContaining([
"repo view --json owner,name,parent|github.acme.internal",
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
+106 -60
View File
@@ -27,6 +27,7 @@ import {
computeChecksStatus,
compareTimelineItems,
createUnavailableSearchResult,
isOnDefaultBranch,
normalizeForgeSearchKinds,
parseOptionalTime,
} from "./forge-service.js";
@@ -34,6 +35,7 @@ import type {
CheckAnnotation,
CheckDetails,
CheckFailedJob,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -446,7 +448,11 @@ const PullRequestTimelineGraphqlSchema = z.object({
.optional(),
});
const GitHubRepoViewSchema = z.object({
const GitHubDefaultBranchSchema = z.object({
defaultBranchRef: z.object({ name: z.string() }).nullish(),
});
const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({
owner: z
.object({
login: z.string().optional(),
@@ -657,7 +663,7 @@ const BatchPollPrNodeSchema = z.object({
isInMergeQueue: z.boolean().optional().catch(false),
});
const BatchPollRepositorySchema = z.object({
const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({
owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null),
isFork: z.boolean().optional().catch(false),
parent: z
@@ -779,9 +785,7 @@ function graphqlString(value: string): string {
return JSON.stringify(value);
}
function buildBatchPullRequestStatusQuery(
entries: Array<{ owner: string; name: string; headRef: string }>,
): string {
function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string {
const aliases = entries.map(
(entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString(
entry.owner,
@@ -789,6 +793,9 @@ function buildBatchPullRequestStatusQuery(
owner {
login
}
defaultBranchRef {
name
}
isFork
parent {
owner {
@@ -802,7 +809,7 @@ function buildBatchPullRequestStatusQuery(
rebaseMergeAllowed
viewerDefaultMergeMethod
pullRequests(headRefName: ${graphqlString(
entry.headRef,
entry.target.headRef,
)}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
...PaseoPollPullRequest
@@ -810,13 +817,26 @@ function buildBatchPullRequestStatusQuery(
}
}`,
);
const originAliases = entries.flatMap((entry, index) =>
entry.owner === entry.originOwner && entry.name === entry.originName
? []
: [
` origin${index}: repository(owner: ${graphqlString(
entry.originOwner,
)}, name: ${graphqlString(entry.originName)}) {
defaultBranchRef {
name
}
}`,
],
);
return `query PaseoBatchPullRequestStatus {
rateLimit {
limit
remaining
resetAt
}
${aliases.join("\n")}
${[...aliases, ...originAliases].join("\n")}
}\n${BATCH_PR_STATUS_FRAGMENT}`;
}
@@ -1076,11 +1096,7 @@ interface InFlightCacheEntry {
force: boolean;
}
interface GitHubPollTarget {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
interface GitHubPollTarget extends CurrentPullRequestLookup {
retainCount: number;
/** Absolute due time on the shared poll grid; null while a poll is in flight. */
nextDueAt: number | null;
@@ -1364,12 +1380,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
});
}
function getPollTargetKey(target: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
}): string {
function getPollTargetKey(target: CurrentPullRequestLookup): string {
return buildCacheKey({
cwd: target.cwd,
method: "getCurrentPullRequestStatus",
@@ -1377,18 +1388,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
},
});
}
function updatePollTargetAfterSuccess(update: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
status: CurrentPullRequestStatus | null;
notify: boolean;
}): void {
function updatePollTargetAfterSuccess(
update: CurrentPullRequestLookup & {
status: CurrentPullRequestStatus | null;
notify: boolean;
},
): void {
const target = pollTargets.get(getPollTargetKey(update));
if (!target) {
return;
@@ -1638,13 +1648,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
if (!firstEntry) {
return;
}
const query = buildBatchPullRequestStatusQuery(
addressedEntries.map((entry) => ({
owner: entry.owner,
name: entry.name,
headRef: entry.target.headRef,
})),
);
const query = buildBatchPullRequestStatusQuery(addressedEntries);
const args = ["api", "graphql", "-f", `query=${query}`];
const response = await loadGitHubPollBatchResponse({
entries: addressedEntries,
@@ -1760,6 +1764,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
}
continue;
}
if (
isTerminalOnDefaultBranch(entry, node, repository.data, input.aliases[`origin${index}`])
) {
finalizeBatchPollTarget({
entry,
node: null,
repository: repository.data,
rollup: null,
startedAt: input.startedAt,
});
continue;
}
const frozenKey =
node.state !== "OPEN" && node.headRefOid.length > 0
? `${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`
@@ -1786,6 +1802,22 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
return distribution;
}
function isTerminalOnDefaultBranch(
entry: GitHubBatchPollEntry,
node: BatchPollPrNode,
repository: BatchPollRepository,
originAlias: unknown,
): boolean {
if (node.state === "OPEN") {
return false;
}
const origin =
entry.owner === entry.originOwner && entry.name === entry.originName
? repository
: GitHubDefaultBranchSchema.safeParse(originAlias).data;
return isOnDefaultBranch(entry.target, origin?.defaultBranchRef?.name);
}
function addressGitHubBatchEntry(entry: GitHubBatchPollEntry): GitHubBatchPollEntry {
const redirect = pollRepositoryRedirects.get(batchRepositoryRedirectKey(entry));
return redirect
@@ -1963,25 +1995,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
);
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
}
const cacheKey = buildCacheKey({
cwd: entry.target.cwd,
method: "getCurrentPullRequestStatus",
args: {
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
},
});
const cacheKey = getPollTargetKey(entry.target);
// A direct or forced read can finish between this batch becoming due and
// its checks query returning. Its cache write is newer than this cycle, so
// converge on it instead of overwriting fresher data with the batch's.
const existing = cache.get(cacheKey);
if (existing && existing.expiresAt - ttlMs > input.startedAt) {
updatePollTargetAfterSuccess({
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
...entry.target,
status: existing.value as CurrentPullRequestStatus | null,
notify: true,
});
@@ -1991,10 +2012,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
// between polls reuse the batch result instead of spawning gh again.
cache.set(cacheKey, { value: status, cwd: entry.target.cwd, expiresAt: deps.now() + ttlMs });
updatePollTargetAfterSuccess({
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
...entry.target,
status,
notify: true,
});
@@ -2007,6 +2025,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
reason: "self-heal-github",
});
} catch (error) {
@@ -2173,14 +2192,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
},
readOptions: input,
load: async () => {
const status = await resolveCurrentPullRequestView({
const status = await loadCurrentPullRequestView({
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
resolveOriginRepo: () => resolveRepoSlugCached(input.cwd),
run,
});
return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run });
@@ -2191,6 +2213,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
status,
notify: input.reason === "self-heal-github",
});
@@ -2603,6 +2626,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
retainCount: 0,
nextDueAt: null,
pollCycleStartedAt: null,
@@ -2984,13 +3008,35 @@ function isGitHubRateLimitError(error: unknown): boolean {
);
}
async function resolveCurrentPullRequestView(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<CurrentPullRequestStatus | null> {
async function loadCurrentPullRequestView(
options: CurrentPullRequestLookup & {
resolveOriginRepo(): Promise<string | null>;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
},
): Promise<CurrentPullRequestStatus | null> {
let repoRead: ReturnType<typeof getGitHubRepoView> | undefined;
const readRepo = () => (repoRead ??= getGitHubRepoView(options));
const status = await resolveCurrentPullRequestView({ ...options, readRepo });
if (!status || status.state === "open") {
return status;
}
const originRepo = await options.resolveOriginRepo();
const repo = await repoRead;
const repoName = repo?.owner?.login && repo.name ? `${repo.owner.login}/${repo.name}` : null;
const origin =
originRepo && originRepo.toLowerCase() !== repoName?.toLowerCase()
? await getGitHubRepoView({ ...options, repo: originRepo })
: await readRepo();
return isOnDefaultBranch(options, origin?.defaultBranchRef?.name) ? null : status;
}
async function resolveCurrentPullRequestView(
options: CurrentPullRequestLookup & {
readRepo(): Promise<z.infer<typeof GitHubRepoViewSchema> | null>;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
},
): Promise<CurrentPullRequestStatus | null> {
const viewCandidate = await tryCurrentPullRequestView(options);
const viewMatch = viewCandidate
? pickPullRequestCandidate({
@@ -3007,7 +3053,7 @@ async function resolveCurrentPullRequestView(options: {
let headRepositoryOwner = options.headRepositoryOwner;
if (!headRepositoryOwner) {
const repo = await getGitHubRepoView(options);
const repo = await options.readRepo();
const forkOwner = repo?.owner?.login;
const parentOwner = repo?.parent?.owner?.login;
const parentName = repo?.parent?.name;
@@ -3282,7 +3328,7 @@ async function readGitHubRepoView(
"view",
...(options.repo ? [options.repo] : []),
"--json",
"owner,name,parent",
"owner,name,parent,defaultBranchRef",
];
const stdout = await options.run(args, {
cwd: options.cwd,
@@ -389,6 +389,26 @@ describe("createGitLabService", () => {
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
});
it("hides a historical MR on the project's default branch", async () => {
const historical = { ...OPEN_MR, state: "merged", source_branch: "trunk" };
const { service } = makeService((args) => {
if (args[1] === "list") return ok(JSON.stringify([historical]));
if (args[1] === "view") return ok(JSON.stringify(historical));
if (args[0] === "api" && args[1] === "projects/example-group%2Fexample-project") {
return ok(
JSON.stringify({
path_with_namespace: "example-group/example-project",
default_branch: "trunk",
}),
);
}
return ok("{}");
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
).resolves.toBeNull();
});
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
const stale = {
...OPEN_MR,
+23 -11
View File
@@ -16,6 +16,7 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
@@ -252,6 +253,7 @@ const GitLabApprovalsSchema = z
const GitLabProjectSchema = z
.object({
path_with_namespace: z.string(),
default_branch: z.string().nullish(),
forked_from_project: z
.object({ path_with_namespace: z.string().optional() })
.nullable()
@@ -1142,6 +1144,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return issues.map(toIssueSummary);
}
async function readOriginProject(cwd: string) {
const remoteUrl = await resolveRemoteUrl(cwd);
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
if (!projectPath) {
return null;
}
return runJson(
["api", `projects/${encodeURIComponent(projectPath)}`],
{ cwd: cwd },
GitLabProjectSchema,
);
}
return {
async isAuthenticated(input: { cwd: string } & ForgeReadOptions): Promise<boolean> {
const glabPath = await resolveGlab();
@@ -1162,17 +1177,8 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
},
async getReferenceRepository(input): Promise<string | null> {
const remoteUrl = await resolveRemoteUrl(input.cwd);
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
if (!projectPath) {
return null;
}
const project = await runJson(
["api", `projects/${encodeURIComponent(projectPath)}`],
{ cwd: input.cwd },
GitLabProjectSchema,
);
return project.forked_from_project?.path_with_namespace ?? null;
const project = await readOriginProject(input.cwd);
return project?.forked_from_project?.path_with_namespace ?? null;
},
async getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
@@ -1181,6 +1187,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
if (!mr) {
return null;
}
if (mapMergeRequestState(mr.state) !== "open") {
const project = await readOriginProject(input.cwd).catch(() => null);
if (isOnDefaultBranch(input, project?.default_branch)) {
return null;
}
}
const [approvals, pipelineChecks] = await Promise.all([
fetchApprovals(input.cwd, mr),
fetchPipelineChecks(input.cwd, mr),
+22 -2
View File
@@ -178,6 +178,7 @@ function createPullRequestStatus(overrides?: Partial<CurrentPullRequestStatus>)
interface RequestedPullRequestTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -194,6 +195,7 @@ function createGitHubServiceRecordingPullRequestTargets(
github.getCurrentPullRequestStatus = async (request) => {
options.requestedTargets.push({
headRef: request.headRef,
...(request.currentBranch ? { currentBranch: request.currentBranch } : {}),
...(request.headSha ? { headSha: request.headSha } : {}),
...(request.headRepositoryOwner ? { headRepositoryOwner: request.headRepositoryOwner } : {}),
});
@@ -3460,7 +3462,7 @@ const x = 1;
{ paseoHome },
);
expect(requestedTargets).toEqual([factsTarget]);
expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]);
});
it("uses the tracked fork branch for PR worktree status lookup", async () => {
@@ -3490,7 +3492,11 @@ const x = 1;
const status = await getPullRequestStatus(repoDir, github);
expect(requestedTargets).toEqual([
expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }),
expect.objectContaining({
headRef: "main",
currentBranch: "chethanuk/main",
headRepositoryOwner: "chethanuk",
}),
]);
expect(status.status?.number).toBe(345);
expect(status.status?.headRefName).toBe("main");
@@ -3521,6 +3527,20 @@ const x = 1;
expect(status.status?.state).toBe("closed");
});
it("looks up PR status again when switching branches at the same commit", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
const requestedTargets: RequestedPullRequestTarget[] = [];
const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets });
const feature = await getPullRequestStatus(repoDir, forge);
execFileSync("git", ["checkout", "main"], { cwd: repoDir });
const main = await getPullRequestStatus(repoDir, forge);
expect(feature.status?.headRefName).toBe("feature");
expect(main.status?.headRefName).toBe("main");
expect(requestedTargets.map(({ headRef }) => headRef)).toEqual(["feature", "main"]);
});
it("caches PR status results for duplicate lookups", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
+18 -12
View File
@@ -153,8 +153,12 @@ function createShortstatCache(ttlMs: number) {
});
}
function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string {
return `${resolve(cwd)}\u0000${headSha ?? ""}`;
function getPullRequestStatusCacheKey(
cwd: string,
currentBranch: string | null,
headSha: string | null,
): string {
return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`;
}
function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void {
@@ -4437,8 +4441,11 @@ export async function getPullRequestStatus(
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
): Promise<PullRequestStatusResult> {
const headSha = await getCurrentHeadSha(cwd, context);
const cacheKey = getPullRequestStatusCacheKey(cwd, headSha);
const [headSha, head] = await Promise.all([
getCurrentHeadSha(cwd, context),
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
]);
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
if (!options?.force) {
const cached = pullRequestStatusCache.get(cacheKey);
if (cached) {
@@ -4451,7 +4458,7 @@ export async function getPullRequestStatus(
}
}
const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha)
const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha)
.then((status) => {
pullRequestStatusCache.set(cacheKey, status);
rememberPullRequestStatus(cacheKey, status);
@@ -4477,6 +4484,7 @@ export async function getPullRequestStatus(
async function getPullRequestStatusUncached(
cwd: string,
forgeService: ForgeService,
head: string | null,
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
headSha?: string | null,
@@ -4486,18 +4494,16 @@ async function getPullRequestStatusUncached(
if (!context?.facts?.isGit) {
await requireGitRepo(cwd, context);
}
const head = context?.facts?.isGit
? context.facts.currentBranch
: await getCurrentBranch(cwd, context);
if (!head) {
return buildPullRequestStatusResult(null, "no_remote");
}
try {
const resolvedLookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head, context);
const lookupTarget =
headSha && !resolvedLookupTarget.headSha
? { ...resolvedLookupTarget, headSha }
: resolvedLookupTarget;
const lookupTarget = {
...resolvedLookupTarget,
...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}),
...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}),
};
let status: CurrentPullRequestStatus | null;
if (options?.force) {
const reason = options.reason;