From 14f466c553cb2749fd87c9b55adcf00359f61273 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Sat, 24 Oct 2026 16:56:50 -0400 Subject: [PATCH 1/5] feat(lib): add mark-PR-ready guard/helpers, gate approve on failing CI, and refine dep status --- mcp/tests/octokit.test.ts | 15 ++++ src/app/lib/dependency-detection.ts | 6 +- src/app/lib/format.ts | 2 +- src/app/services/api-usage.ts | 3 +- src/app/services/github.ts | 54 ++++++++----- src/shared/format.ts | 14 +++- src/shared/validation.ts | 11 +++ tests/lib/dependency-detection.test.ts | 31 +++++++- tests/lib/format.test.ts | 84 +++++++++++++++++++- tests/services/github.test.ts | 102 ++++++++++++++++++++++++- 10 files changed, 292 insertions(+), 30 deletions(-) diff --git a/mcp/tests/octokit.test.ts b/mcp/tests/octokit.test.ts index 1bf6c1a0..a0a6c356 100644 --- a/mcp/tests/octokit.test.ts +++ b/mcp/tests/octokit.test.ts @@ -92,6 +92,21 @@ describe("createOctokitClient — write guard hook", () => { }) ).rejects.toThrow(/Write operation blocked/); }); + + it("blocks MARK_PR_READY_MUTATION (markPullRequestReadyForReview) on POST /graphql", async () => { + const { createOctokitClient } = await import("../src/octokit.js"); + const { MARK_PR_READY_MUTATION } = await import("../../src/shared/validation.js"); + const client = createOctokitClient("fake-token"); + + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { + pullRequestId: "PR_kwDOtest42", + }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── Singleton tests ─────────────────────────────────────────────────────────── diff --git a/src/app/lib/dependency-detection.ts b/src/app/lib/dependency-detection.ts index 8182ca7e..0dd1827e 100644 --- a/src/app/lib/dependency-detection.ts +++ b/src/app/lib/dependency-detection.ts @@ -282,12 +282,12 @@ export function classifyDepStatus( return "pending-rebase"; } - // 2. Enriched + CI green + not draft + not approved → mergeable + // 2. Enriched + CI green (or no CI configured) + not draft + not changes-requested → mergeable if ( pr.enriched !== false && !pr.draft && - pr.checkStatus === "success" && - pr.reviewDecision !== "APPROVED" + (pr.checkStatus === "success" || pr.checkStatus === null) && + pr.reviewDecision !== "CHANGES_REQUESTED" ) { return "mergeable"; } diff --git a/src/app/lib/format.ts b/src/app/lib/format.ts index a3a7dd2b..40216f1b 100644 --- a/src/app/lib/format.ts +++ b/src/app/lib/format.ts @@ -1,5 +1,5 @@ // Re-exports from shared/format for backward compat with existing importers. -export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, canApprovePR } from "../../shared/format"; +export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, canApprovePR, canMarkPRReady } from "../../shared/format"; export function stripParenthetical(name: string): string { return name.replace(/\s*\(.*\)$/, ""); diff --git a/src/app/services/api-usage.ts b/src/app/services/api-usage.ts index b52a2878..11c8a84a 100644 --- a/src/app/services/api-usage.ts +++ b/src/app/services/api-usage.ts @@ -9,7 +9,7 @@ import { onApiRequest, type ApiRequestInfo } from "./github"; const API_CALL_SOURCES = [ "lightSearch", "heavyBackfill", "forkCheck", "globalUserSearch", "unfilteredSearch", "upstreamDiscovery", "workflowRuns", "hotPRStatus", "hotRunStatus", "userEvents", - "validateUser", "fetchOrgs", "fetchRepos", "rateLimitCheck", "approvePR", "graphql", "rest", + "validateUser", "fetchOrgs", "fetchRepos", "rateLimitCheck", "approvePR", "markPRReady", "graphql", "rest", ] as const; export type ApiCallSource = (typeof API_CALL_SOURCES)[number]; @@ -34,6 +34,7 @@ export const SOURCE_LABELS: Record = { fetchRepos: "Fetch Repos", rateLimitCheck: "Rate Limit Check", approvePR: "Approve PR", + markPRReady: "Mark PR Ready", graphql: "GraphQL (other)", rest: "REST (other)", }; diff --git a/src/app/services/github.ts b/src/app/services/github.ts index 563d57bb..b185e58f 100644 --- a/src/app/services/github.ts +++ b/src/app/services/github.ts @@ -6,11 +6,13 @@ import { paginateRest } from "@octokit/plugin-paginate-rest"; import { cachedFetch, type ConditionalHeaders } from "../stores/cache"; import { token } from "../stores/auth"; import { pushNotification } from "../lib/errors"; -import { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery } from "../../shared/validation"; +import { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery } from "../../shared/validation"; -export { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery }; +export { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery }; const NORMALIZED_APPROVE_MUTATION = APPROVE_PR_MUTATION.replace(/\s+/g, " "); +const NORMALIZED_MARK_READY_MUTATION = MARK_PR_READY_MUTATION.replace(/\s+/g, " "); +const APPROVE_ALLOWED_KEYS = new Set(["pullRequestId", "commitOID", "event"]); function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown }): boolean { if (typeof options.query !== "string") return false; @@ -20,26 +22,42 @@ function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown return true; } - // 2. Allow ONLY the exact canonical ApprovePullRequest mutation + // 2. Allow ONLY the exact canonical ApprovePullRequest or MarkPullRequestReadyForReview mutations const stripped = options.query.replace(/#[^\r\n]*/g, "").trim(); const normalized = stripped.replace(/\s+/g, " "); - if (normalized !== NORMALIZED_APPROVE_MUTATION) { - return false; - } // 3. Validate mutation variables const vars = options.variables as Record | undefined; - if (!vars || typeof vars !== "object") return false; - if (typeof vars.pullRequestId !== "string" || !GITHUB_NODE_ID_RE.test(vars.pullRequestId)) { - return false; - } - if (typeof vars.commitOID !== "string" || !GIT_SHA_RE.test(vars.commitOID)) { - return false; + if (!vars || typeof vars !== "object" || Array.isArray(vars)) return false; + + if (normalized === NORMALIZED_APPROVE_MUTATION) { + if (!Object.keys(vars).every((k) => APPROVE_ALLOWED_KEYS.has(k))) { + return false; + } + if (typeof vars.pullRequestId !== "string" || !GITHUB_NODE_ID_RE.test(vars.pullRequestId)) { + return false; + } + if (typeof vars.commitOID !== "string" || !GIT_SHA_RE.test(vars.commitOID)) { + return false; + } + if (vars.event !== undefined && vars.event !== "APPROVE") { + return false; + } + return true; } - if (vars.event !== undefined && vars.event !== "APPROVE") { - return false; + + if (normalized === NORMALIZED_MARK_READY_MUTATION) { + const keys = Object.keys(vars); + if (keys.length !== 1 || keys[0] !== "pullRequestId") { + return false; + } + if (typeof vars.pullRequestId !== "string" || !GITHUB_NODE_ID_RE.test(vars.pullRequestId)) { + return false; + } + return true; } - return true; + + return false; } // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -169,13 +187,13 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { }); // Least-privilege write guard: the OAuth App `repo` scope grants broad write access, - // but this app only permits GET requests, read-only GraphQL queries, and the single - // explicit user-confirmed PR approval mutation (APPROVE_PR_MUTATION). + // but this app only permits GET requests, read-only GraphQL queries, and explicit + // user-confirmed mutations (APPROVE_PR_MUTATION and MARK_PR_READY_MUTATION). client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; if (method === "POST" && options.url === "/graphql" && isAllowedGraphqlRequest(options)) return; - throw new Error(`[github] Write operation blocked: ${method} ${options.url}. Only read queries and PR approvals are permitted.`); + throw new Error(`[github] Write operation blocked: ${method} ${options.url}. Only read queries, PR approvals, and marking draft PRs ready are permitted.`); }); // Track every API request for usage analytics + update rate limit display diff --git a/src/shared/format.ts b/src/shared/format.ts index d23f4f99..2d972114 100644 --- a/src/shared/format.ts +++ b/src/shared/format.ts @@ -140,7 +140,7 @@ export function formatStarCount(count: number): string { /** * Returns true when the authenticated user can approve the given PR from a row action: - * - PR is OPEN, enriched, not a draft, and has a valid GraphQL nodeId + headSha + * - PR is OPEN, enriched, not a draft, CI checks are not failing, and has a valid GraphQL nodeId + headSha * - Authenticated user is not the PR author (case-insensitive) * - Viewer has not already approved the PR without a fresh review request * (`!(viewerLatestReviewState === "APPROVED" && !viewerReviewRequested)`) @@ -151,7 +151,19 @@ export function canApprovePR(pr: PullRequest, userLogin: string): boolean { if (!userLogin || !pr.nodeId || !pr.headSha) return false; if (pr.enriched === false) return false; if (pr.state !== "OPEN" || pr.draft) return false; + if (pr.checkStatus === "failure") return false; if (pr.userLogin.toLowerCase() === userLogin.toLowerCase()) return false; if (pr.viewerLatestReviewState === "APPROVED" && !pr.viewerReviewRequested) return false; return pr.reviewDecision === "REVIEW_REQUIRED" || pr.viewerReviewRequested === true; } + +/** + * Returns true when the authenticated user can mark a draft PR as ready for review: + * - PR is OPEN, currently a draft, and has a valid GraphQL nodeId + * - Authenticated user is the PR author (case-insensitive) + */ +export function canMarkPRReady(pr: PullRequest, userLogin: string): boolean { + if (!userLogin || !pr.nodeId) return false; + if (pr.state !== "OPEN" || !pr.draft) return false; + return pr.userLogin.toLowerCase() === userLogin.toLowerCase(); +} diff --git a/src/shared/validation.ts b/src/shared/validation.ts index eecae657..8b872852 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -22,6 +22,17 @@ export const APPROVE_PR_MUTATION = ` } `.trim(); +export const MARK_PR_READY_MUTATION = ` + mutation MarkPullRequestReadyForReview($pullRequestId: ID!) { + markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) { + pullRequest { + isDraft + reviewDecision + } + } + } +`.trim(); + export const GITHUB_NODE_ID_RE = /^(?:PR_[A-Za-z0-9_-]{4,120}|[A-Za-z0-9+/=_-]{8,128})$/; export const GIT_SHA_RE = /^[0-9a-f]{40}$/i; diff --git a/tests/lib/dependency-detection.test.ts b/tests/lib/dependency-detection.test.ts index cb7a3a79..008bf56d 100644 --- a/tests/lib/dependency-detection.test.ts +++ b/tests/lib/dependency-detection.test.ts @@ -456,16 +456,28 @@ describe("classifyDepStatus", () => { expect(classifyDepStatus(pr, "", 14)).toBe("needs-action"); }); - it("returns needs-action for unenriched PR (enriched=false, checkStatus is null)", () => { + it("returns needs-action for unenriched PR (enriched=false, draft=false, checkStatus is null)", () => { const pr = makePullRequest({ enriched: false, + draft: false, checkStatus: null, updatedAt: RECENT, }); expect(classifyDepStatus(pr, "", 14)).toBe("needs-action"); }); - it("returns needs-action for approved PR (already handled, not mergeable)", () => { + it("returns mergeable for enriched non-draft PR with checkStatus null (no CI configured)", () => { + const pr = makePullRequest({ + enriched: true, + draft: false, + checkStatus: null, + reviewDecision: null, + updatedAt: RECENT, + }); + expect(classifyDepStatus(pr, "", 14)).toBe("mergeable"); + }); + + it("returns mergeable for approved PR with passing CI", () => { const pr = makePullRequest({ enriched: true, draft: false, @@ -473,15 +485,26 @@ describe("classifyDepStatus", () => { reviewDecision: "APPROVED", updatedAt: RECENT, }); + expect(classifyDepStatus(pr, "", 14)).toBe("mergeable"); + }); + + it("returns needs-action for recent PR with changes requested even when CI is green", () => { + const pr = makePullRequest({ + enriched: true, + draft: false, + checkStatus: "success", + reviewDecision: "CHANGES_REQUESTED", + updatedAt: RECENT, + }); expect(classifyDepStatus(pr, "", 14)).toBe("needs-action"); }); - it("returns stale for approved PR that has not been updated in over 14 days", () => { + it("returns stale for PR with changes requested that has not been updated in over 14 days", () => { const pr = makePullRequest({ enriched: true, draft: false, checkStatus: "success", - reviewDecision: "APPROVED", + reviewDecision: "CHANGES_REQUESTED", updatedAt: OLD, }); expect(classifyDepStatus(pr, "", 14)).toBe("stale"); diff --git a/tests/lib/format.test.ts b/tests/lib/format.test.ts index e24b6a91..c381d787 100644 --- a/tests/lib/format.test.ts +++ b/tests/lib/format.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary, canApprovePR } from "../../src/app/lib/format"; +import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary, canApprovePR, canMarkPRReady } from "../../src/app/lib/format"; import { makePullRequest } from "../helpers/factories"; describe("relativeTime", () => { @@ -577,4 +577,86 @@ describe("canApprovePR", () => { expect(canApprovePR(noHeadSha, "reviewer")).toBe(false); expect(canApprovePR(validPr, "")).toBe(false); }); + + it("returns false when checkStatus is failure and true for success, pending, conflict, or null", () => { + const base = { + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED" as const, + }; + + expect(canApprovePR(makePullRequest({ ...base, checkStatus: "failure" }), "reviewer")).toBe(false); + expect(canApprovePR(makePullRequest({ ...base, checkStatus: "success" }), "reviewer")).toBe(true); + expect(canApprovePR(makePullRequest({ ...base, checkStatus: "pending" }), "reviewer")).toBe(true); + expect(canApprovePR(makePullRequest({ ...base, checkStatus: "conflict" }), "reviewer")).toBe(true); + expect(canApprovePR(makePullRequest({ ...base, checkStatus: null }), "reviewer")).toBe(true); + }); +}); + +describe("canMarkPRReady", () => { + it("returns true for an OPEN draft PR authored by userLogin (case-insensitive)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + state: "OPEN", + draft: true, + userLogin: "OctoCat", + }); + expect(canMarkPRReady(pr, "octocat")).toBe(true); + expect(canMarkPRReady(pr, "OCTOCAT")).toBe(true); + }); + + it("returns false when userLogin is not the PR author", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + state: "OPEN", + draft: true, + userLogin: "author", + }); + expect(canMarkPRReady(pr, "reviewer")).toBe(false); + }); + + it("returns false when draft is false", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + state: "OPEN", + draft: false, + userLogin: "octocat", + }); + expect(canMarkPRReady(pr, "octocat")).toBe(false); + }); + + it("returns false when PR state is CLOSED or MERGED", () => { + const closedPr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + state: "CLOSED", + draft: true, + userLogin: "octocat", + }); + const mergedPr = makePullRequest({ + nodeId: "PR_kwDOtest0002", + state: "MERGED", + draft: true, + userLogin: "octocat", + }); + expect(canMarkPRReady(closedPr, "octocat")).toBe(false); + expect(canMarkPRReady(mergedPr, "octocat")).toBe(false); + }); + + it("returns false when nodeId is missing or userLogin is empty", () => { + const noNodeId = makePullRequest({ + nodeId: undefined, + state: "OPEN", + draft: true, + userLogin: "octocat", + }); + const validDraft = makePullRequest({ + nodeId: "PR_kwDOtest0001", + state: "OPEN", + draft: true, + userLogin: "octocat", + }); + expect(canMarkPRReady(noNodeId, "octocat")).toBe(false); + expect(canMarkPRReady(validDraft, "")).toBe(false); + }); }); diff --git a/tests/services/github.test.ts b/tests/services/github.test.ts index d8a76f3c..9be7771e 100644 --- a/tests/services/github.test.ts +++ b/tests/services/github.test.ts @@ -1,7 +1,7 @@ import "fake-indexeddb/auto"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { createRoot } from "solid-js"; -import { createGitHubClient, cachedRequest, getClient, initClientWatcher, getGraphqlRateLimit, updateGraphqlRateLimit, updateRateLimitFromHeaders, getCoreRateLimit, fetchRateLimitDetails, onApiRequest, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, type ApiRequestInfo } from "../../src/app/services/github"; +import { createGitHubClient, cachedRequest, getClient, initClientWatcher, getGraphqlRateLimit, updateGraphqlRateLimit, updateRateLimitFromHeaders, getCoreRateLimit, fetchRateLimitDetails, onApiRequest, APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, type ApiRequestInfo } from "../../src/app/services/github"; import { clearCache } from "../../src/app/stores/cache"; // ── createGitHubClient ─────────────────────────────────────────────────────── @@ -211,6 +211,106 @@ describe("createGitHubClient", () => { variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha, event: "REQUEST_CHANGES" }, }) ).rejects.toThrow(/Write operation blocked/); + + // Unexpected extra variable on APPROVE_PR_MUTATION + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha, extra: "unexpected" }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Array variables on APPROVE_PR_MUTATION + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: ["PR_kwDOtest42", validSha] as unknown as Record, + }) + ).rejects.toThrow(/Write operation blocked/); + }); + + it("allows MARK_PR_READY_MUTATION with valid PR_ or legacy Base64 nodeId", async () => { + const client = createGitHubClient("test-token"); + const mockFetch = vi.fn().mockImplementation(async () => + new Response( + JSON.stringify({ + data: { + markPullRequestReadyForReview: { + pullRequest: { isDraft: false, reviewDecision: "REVIEW_REQUIRED" }, + }, + }, + }), + { status: 200, headers: { "content-type": "application/json" } } + ) + ); + vi.stubGlobal("fetch", mockFetch); + + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42" }, + }) + ).resolves.toBeDefined(); + + await expect( + client.graphql(MARK_PR_READY_MUTATION, { + pullRequestId: "MDExOlB1bGxSZXF1ZXN0NDI=", + }) + ).resolves.toBeDefined(); + + expect(MARK_PR_READY_MUTATION).not.toContain("rateLimit"); + vi.unstubAllGlobals(); + }); + + it("blocks MARK_PR_READY_MUTATION with missing, malformed, array, or extra variables", async () => { + const client = createGitHubClient("test-token"); + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + // Missing variables object + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Empty variables object + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: {}, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Malformed pullRequestId + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { pullRequestId: "bad!id" }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Extra unexpected variable (e.g. commitOID or extra) + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", extra: "unexpected" }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Array variables + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: ["PR_kwDOtest42"] as unknown as Record, + }) + ).rejects.toThrow(/Write operation blocked/); }); }); From c9654b573ea919d8096b28990254ad1c945855ab Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Sat, 24 Oct 2026 17:07:42 -0400 Subject: [PATCH 2/5] feat(api): add markPullRequestReady mutation and hot-poll isDraft tracking --- src/app/services/api.ts | 43 +++++++++++++++++- src/app/services/poll.ts | 2 +- tests/services/api.test.ts | 80 ++++++++++++++++++++++++++++++++- tests/services/hot-poll.test.ts | 73 ++++++++++++++++++++++++++++++ 4 files changed, 195 insertions(+), 3 deletions(-) diff --git a/src/app/services/api.ts b/src/app/services/api.ts index d27ec4c6..e0e32fcf 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -3,7 +3,7 @@ import * as Sentry from "@sentry/solid"; import { pushNotification } from "../lib/errors"; import type { ApiCallSource } from "./api-usage"; import type { TrackedUser } from "../stores/config"; -import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; +import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP, APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; import { REPO_CAP } from "../../shared/types"; import type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; @@ -422,6 +422,7 @@ const HOT_PR_STATUS_QUERY = ` ... on PullRequest { databaseId state + isDraft headRefOid mergeStateStatus reviewDecision @@ -444,6 +445,7 @@ const HOT_PR_STATUS_QUERY = ` interface HotPRStatusNode { databaseId: number; state: PullRequestState; + isDraft?: boolean; headRefOid?: string; mergeStateStatus: string; reviewDecision: string | null; @@ -1979,6 +1981,7 @@ export async function fetchWorkflowRuns( export interface HotPRStatusUpdate { state: PullRequestState; + draft?: boolean; checkStatus: CheckStatus["status"]; mergeStateStatus: string; reviewDecision: PullRequest["reviewDecision"]; @@ -2019,6 +2022,7 @@ export async function fetchHotPRStatus( results.set(node.databaseId, { state: node.state, + ...(typeof node.isDraft === "boolean" ? { draft: node.isDraft } : {}), checkStatus, mergeStateStatus: node.mergeStateStatus, reviewDecision: mapReviewDecision(node.reviewDecision), @@ -2273,3 +2277,40 @@ export async function approvePullRequest( reviewDecision: mapReviewDecision(review?.pullRequest?.reviewDecision ?? null), }; } + +interface MarkPullRequestReadyResponse { + markPullRequestReadyForReview: { + pullRequest: { + isDraft: boolean | null; + reviewDecision: string | null; + } | null; + } | null; + rateLimit?: GraphQLRateLimit; +} + +export async function markPullRequestReady( + octokit: GitHubOctokit, + pullRequestId: string, +): Promise<{ draft: false; reviewDecision: PullRequest["reviewDecision"] }> { + if (!GITHUB_NODE_ID_RE.test(pullRequestId)) { + throw new Error(`Invalid pullRequestId: "${pullRequestId}"`); + } + + const response = await octokit.graphql(MARK_PR_READY_MUTATION, { + pullRequestId, + request: { apiSource: "markPRReady", retries: 0 }, + }); + + if (response.rateLimit) { + updateGraphqlRateLimit(response.rateLimit); + } + + const pr = response.markPullRequestReadyForReview?.pullRequest; + if (!pr || pr.isDraft !== false) { + throw new Error("GitHub did not confirm pull request is ready for review"); + } + return { + draft: false, + reviewDecision: mapReviewDecision(pr.reviewDecision ?? null), + }; +} diff --git a/src/app/services/poll.ts b/src/app/services/poll.ts index b622db5a..cfb33dbf 100644 --- a/src/app/services/poll.ts +++ b/src/app/services/poll.ts @@ -547,7 +547,7 @@ export async function fetchHotData(priorConsecutiveFailures = 0): Promise<{ if ( upd.state === "CLOSED" || upd.state === "MERGED" || - (upd.checkStatus !== "pending" && upd.checkStatus !== null) + upd.checkStatus !== "pending" ) { const nodeId = _hotPRsByDbId.get(databaseId); if (nodeId) { diff --git a/tests/services/api.test.ts b/tests/services/api.test.ts index 69b849e8..3df0a8da 100644 --- a/tests/services/api.test.ts +++ b/tests/services/api.test.ts @@ -8,10 +8,11 @@ import { fetchPREnrichment, fetchHotPRStatus, approvePullRequest, + markPullRequestReady, discoverUpstreamRepos, type RepoRef, } from "../../src/app/services/api"; -import { APPROVE_PR_MUTATION } from "../../src/app/services/github"; +import { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION } from "../../src/app/services/github"; import { clearCache } from "../../src/app/stores/cache"; import { pushNotification } from "../../src/app/lib/errors"; @@ -1577,3 +1578,80 @@ describe("approvePullRequest", () => { ).rejects.toThrow("GitHub did not confirm pull request approval"); }); }); + +// ── markPullRequestReady ────────────────────────────────────────────────────── + +describe("markPullRequestReady", () => { + it("executes MARK_PR_READY_MUTATION with retries: 0, updates rateLimit, and returns draft: false + reviewDecision", async () => { + const githubModule = await import("../../src/app/services/github"); + const updateSpy = vi.spyOn(githubModule, "updateGraphqlRateLimit"); + + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + markPullRequestReadyForReview: { + pullRequest: { + isDraft: false, + reviewDecision: "REVIEW_REQUIRED", + }, + }, + rateLimit: { cost: 1, limit: 5000, remaining: 4987, resetAt: "2026-04-23T12:00:00Z" }, + }) + ); + + const result = await markPullRequestReady(octokit as never, "PR_kwDOtest0042"); + + expect(octokit.graphql).toHaveBeenCalledWith(MARK_PR_READY_MUTATION, { + pullRequestId: "PR_kwDOtest0042", + request: { apiSource: "markPRReady", retries: 0 }, + }); + expect(updateSpy).toHaveBeenCalledWith( + expect.objectContaining({ limit: 5000, remaining: 4987, resetAt: "2026-04-23T12:00:00Z" }) + ); + expect(result).toEqual({ + draft: false, + reviewDecision: "REVIEW_REQUIRED", + }); + }); + + it("rejects invalid pullRequestId before calling octokit.graphql", async () => { + const octokit = makeOctokit(async () => ({ data: {} })); + + await expect( + markPullRequestReady(octokit as never, "bad!id") + ).rejects.toThrow("Invalid pullRequestId"); + + expect(octokit.graphql).not.toHaveBeenCalled(); + }); + + it("throws when pullRequest is null or isDraft is true", async () => { + const octokitStillDraft = makeOctokit( + async () => ({ data: {} }), + async () => ({ + markPullRequestReadyForReview: { + pullRequest: { + isDraft: true, + reviewDecision: null, + }, + }, + }) + ); + + await expect( + markPullRequestReady(octokitStillDraft as never, "PR_kwDOtest0042") + ).rejects.toThrow("GitHub did not confirm pull request is ready for review"); + + const octokitNullPR = makeOctokit( + async () => ({ data: {} }), + async () => ({ + markPullRequestReadyForReview: { + pullRequest: null, + }, + }) + ); + + await expect( + markPullRequestReady(octokitNullPR as never, "PR_kwDOtest0042") + ).rejects.toThrow("GitHub did not confirm pull request is ready for review"); + }); +}); diff --git a/tests/services/hot-poll.test.ts b/tests/services/hot-poll.test.ts index a5d351e4..27afb998 100644 --- a/tests/services/hot-poll.test.ts +++ b/tests/services/hot-poll.test.ts @@ -247,6 +247,45 @@ describe("fetchHotPRStatus", () => { expect(u47.viewerLatestReviewState).toBeNull(); expect(u47.viewerReviewRequested).toBe(false); }); + + it("requests isDraft in HOT_PR_STATUS_QUERY and maps isDraft to draft on HotPRStatusUpdate", async () => { + const octokit = makeOctokit(undefined, () => Promise.resolve({ + nodes: [ + { + databaseId: 48, + state: "OPEN", + isDraft: false, + mergeStateStatus: "CLEAN", + reviewDecision: "REVIEW_REQUIRED", + commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + }, + { + databaseId: 49, + state: "OPEN", + isDraft: true, + mergeStateStatus: "CLEAN", + reviewDecision: null, + commits: { nodes: [] }, + }, + { + databaseId: 50, + state: "OPEN", + mergeStateStatus: "CLEAN", + reviewDecision: null, + commits: { nodes: [] }, + }, + ], + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-01-01T00:00:00Z" }, + })); + + const { results } = await fetchHotPRStatus(octokit as never, ["PR_node7", "PR_node8", "PR_node9"]); + const calledQuery = octokit.graphql.mock.calls[0][0] as string; + expect(calledQuery).toContain("isDraft"); + + expect(results.get(48)!.draft).toBe(false); + expect(results.get(49)!.draft).toBe(true); + expect(results.get(50)!.draft).toBeUndefined(); + }); }); describe("fetchWorkflowRunById", () => { @@ -483,6 +522,40 @@ describe("fetchHotData", () => { expect(graphqlFn).not.toHaveBeenCalled(); }); + it("evicts OPEN PRs from hot set when checkStatus is null (no CI checks configured)", async () => { + const graphqlFn = vi.fn(() => Promise.resolve({ + nodes: [{ + databaseId: 2, + state: "OPEN", + isDraft: false, + mergeStateStatus: "CLEAN", + reviewDecision: null, + commits: { nodes: [{ commit: { statusCheckRollup: null } }] }, + }], + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-01-01T00:00:00Z" }, + })); + const octokit = makeOctokit(undefined, graphqlFn); + mockGetClient.mockReturnValue(octokit); + + // Seed PR into _hotPRs (e.g. synthetically seeded with pending checkStatus before hot poll confirms no CI) + rebuildHotSets({ + ...emptyData, + pullRequests: [makePullRequest({ id: 2, checkStatus: "pending", enriched: true, nodeId: "PR_no_ci" })], + }); + + // First fetch — PR is OPEN with checkStatus: null -> evicts after single cycle + const first = await fetchHotData(); + expect(first.prUpdates.size).toBe(1); + expect(first.prUpdates.get(2)!.checkStatus).toBeNull(); + expect(first.prUpdates.get(2)!.draft).toBe(false); + + // Second fetch — PR was evicted, should not query again + graphqlFn.mockClear(); + const second = await fetchHotData(); + expect(second.prUpdates.size).toBe(0); + expect(graphqlFn).not.toHaveBeenCalled(); + }); + it("evicts runs from hot set when status becomes completed", async () => { const requestFn = vi.fn(() => Promise.resolve({ data: { id: 10, status: "completed", conclusion: "success", updated_at: "2026-01-01T00:05:00Z", completed_at: "2026-01-01T00:05:00Z" }, From 0ca497744a0ddda4a3bbcca4bb0141a3f5d885b9 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Sat, 24 Oct 2026 17:17:13 -0400 Subject: [PATCH 3/5] feat(ui): add two-step clickable DraftBadge and dependencies action reason badges --- .../components/dashboard/DependenciesTab.tsx | 36 +++- .../components/dashboard/PullRequestsTab.tsx | 28 ++- src/app/components/dashboard/TrackedTab.tsx | 26 ++- src/app/components/shared/DraftBadge.tsx | 146 ++++++++++++++++ tests/components/PullRequestsTab.test.tsx | 114 ++++++++++++ .../dashboard/DependenciesTab.test.tsx | 160 +++++++++++++++++ .../components/dashboard/TrackedTab.test.tsx | 111 ++++++++++++ tests/components/shared-badges.test.tsx | 164 ++++++++++++++++++ 8 files changed, 764 insertions(+), 21 deletions(-) create mode 100644 src/app/components/shared/DraftBadge.tsx diff --git a/src/app/components/dashboard/DependenciesTab.tsx b/src/app/components/dashboard/DependenciesTab.tsx index b1ddd204..6ff6227a 100644 --- a/src/app/components/dashboard/DependenciesTab.tsx +++ b/src/app/components/dashboard/DependenciesTab.tsx @@ -3,7 +3,7 @@ import { config, updateConfig } from "../../stores/config"; import { viewState, setTabFilter, resetAllTabFilters, ignoreItem, unignoreItem, trackItem, untrackItem, DependencyFiltersSchema, setDependencyExpandedGroups } from "../../stores/view"; import IgnoreBadge from "./IgnoreBadge"; import { isSafeGitHubUrl } from "../../lib/url"; -import { canApprovePR } from "../../lib/format"; +import { canApprovePR, canMarkPRReady } from "../../lib/format"; import type { PullRequest } from "../../services/api"; import type { AbandonedDependency } from "../../lib/dependency-dashboard"; import { @@ -25,6 +25,7 @@ import StatusDot from "../shared/StatusDot"; import SizeBadge from "../shared/SizeBadge"; import ReviewBadge from "../shared/ReviewBadge"; import AutoMergeBadge from "../shared/AutoMergeBadge"; +import DraftBadge from "../shared/DraftBadge"; import ItemRow from "./ItemRow"; import SkeletonRows from "../shared/SkeletonRows"; @@ -114,6 +115,8 @@ interface DependenciesTabProps { onRefresh?: () => void; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } export default function DependenciesTab(props: DependenciesTabProps) { @@ -370,6 +373,8 @@ export default function DependenciesTab(props: DependenciesTabProps) { userLogin={props.userLogin} onApprovePR={props.onApprovePR} approvingPRIds={props.approvingPRIds} + onMarkPRReady={props.onMarkPRReady} + markingReadyPRIds={props.markingReadyPRIds} /> )} @@ -395,6 +400,8 @@ interface StatusGroupProps { userLogin: string; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } function stripCommitPrefix(title: string): string { @@ -463,9 +470,23 @@ function StatusGroup(props: StatusGroupProps) { >
- + + + + + Merge conflict + + + + Failing checks + + + Checks running + 0 || pr.deletions > 0)}> @@ -476,9 +497,14 @@ function StatusGroup(props: StatusGroupProps) { /> - - Draft - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> ; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } type SortField = "repo" | "title" | "author" | "createdAt" | "updatedAt" | "checkStatus" | "reviewDecision" | "size"; @@ -561,11 +564,13 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { - - - Draft - - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> 0}> @@ -593,9 +598,14 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { - - D - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> 0 || (prMeta().get(pr.id)?.roles ?? []).length > 0)}> 0 ? `Role: ${(prMeta().get(pr.id)?.roles ?? []).join(", ")}` : false, diff --git a/src/app/components/dashboard/TrackedTab.tsx b/src/app/components/dashboard/TrackedTab.tsx index d1301896..eb3063ee 100644 --- a/src/app/components/dashboard/TrackedTab.tsx +++ b/src/app/components/dashboard/TrackedTab.tsx @@ -3,12 +3,13 @@ import { config } from "../../stores/config"; import { viewState, untrackItem, moveTrackedItem, untrackJiraItem, moveJiraItem } from "../../stores/view"; import type { TrackedItem } from "../../stores/view"; import type { Issue, PullRequest } from "../../services/api"; -import { canApprovePR, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, canMarkPRReady, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; import { isSafeGitHubUrl } from "../../lib/url"; import ItemRow from "./ItemRow"; import StatusDot from "../shared/StatusDot"; import ReviewBadge from "../shared/ReviewBadge"; import AutoMergeBadge from "../shared/AutoMergeBadge"; +import DraftBadge from "../shared/DraftBadge"; import SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import { Tooltip } from "../shared/Tooltip"; @@ -79,6 +80,8 @@ export interface TrackedTabProps { hotPollingPRIds?: ReadonlySet; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } export default function TrackedTab(props: TrackedTabProps) { @@ -291,9 +294,13 @@ export default function TrackedTab(props: TrackedTabProps) { - - Draft - + props.onMarkPRReady!(prData()) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(prData().id)} + />
} > @@ -312,9 +319,14 @@ export default function TrackedTab(props: TrackedTabProps) { - - D - + props.onMarkPRReady!(prData()) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(prData().id)} + /> ); diff --git a/src/app/components/shared/DraftBadge.tsx b/src/app/components/shared/DraftBadge.tsx new file mode 100644 index 00000000..97621585 --- /dev/null +++ b/src/app/components/shared/DraftBadge.tsx @@ -0,0 +1,146 @@ +import { createEffect, createMemo, createSignal, on, onCleanup, Show } from "solid-js"; +import { Tooltip } from "./Tooltip"; + +export interface DraftBadgeProps { + draft: boolean; + compact?: boolean; + prNumber?: number; + prTitle?: string; + /** Defined only when canMarkPRReady(pr, userLogin) is true */ + onMarkReady?: () => void; + /** True while markPullRequestReady mutation is in flight for this PR */ + isMarkingReady?: boolean; +} + +const READY_CONFIRM_TIMEOUT_MS = 4_000; + +export default function DraftBadge(props: DraftBadgeProps) { + const [confirming, setConfirming] = createSignal(false); + let confirmTimer: ReturnType | undefined; + + function clearTimer() { + if (confirmTimer !== undefined) { + clearTimeout(confirmTimer); + confirmTimer = undefined; + } + } + + function resetConfirm() { + clearTimer(); + setConfirming(false); + } + + const isMarkingReady = createMemo(() => Boolean(props.isMarkingReady)); + + createEffect( + on( + [() => props.draft, () => props.onMarkReady, isMarkingReady], + (curr, prev) => { + if (!prev || curr.some((v, i) => v !== prev[i])) { + resetConfirm(); + } + }, + { defer: true }, + ), + ); + + onCleanup(clearTimer); + + function handleClick(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + if (props.isMarkingReady || !props.onMarkReady) return; + if (!confirming()) { + setConfirming(true); + clearTimer(); + confirmTimer = setTimeout(() => { + confirmTimer = undefined; + setConfirming(false); + }, READY_CONFIRM_TIMEOUT_MS); + return; + } + resetConfirm(); + props.onMarkReady(); + } + + function handleKeyDown(e: KeyboardEvent) { + if (e.key === "Escape" && confirming()) { + e.stopPropagation(); + e.preventDefault(); + resetConfirm(); + } + } + + const meta = createMemo(() => { + const target = [props.prNumber != null ? `#${props.prNumber}` : "", props.prTitle ?? ""] + .filter(Boolean) + .join(" "); + const labelTarget = target ? ` ${target}` : ""; + const sizeClass = props.compact ? "badge-xs" : "badge-sm"; + + if (props.isMarkingReady) { + return { + tooltip: "Marking ready for review...", + ariaLabel: `Marking${labelTarget} ready for review`, + buttonClass: `badge badge-ghost ${sizeClass}`, + }; + } + + if (confirming()) { + return { + tooltip: "Click again to mark ready for review", + ariaLabel: `Confirm mark${labelTarget} ready for review`, + buttonClass: `badge badge-warning cursor-pointer font-medium ${sizeClass}`, + }; + } + + return { + tooltip: "Click to mark ready for review", + ariaLabel: `Mark${labelTarget} ready for review`, + buttonClass: `badge badge-ghost italic text-base-content/70 hover:badge-info hover:not-italic hover:text-info-content cursor-pointer transition-colors ${sizeClass}`, + }; + }); + + return ( + + + {props.compact ? "D" : "Draft"} + + } + > + + + + + + ); +} diff --git a/tests/components/PullRequestsTab.test.tsx b/tests/components/PullRequestsTab.test.tsx index 22a7de99..40e41464 100644 --- a/tests/components/PullRequestsTab.test.tsx +++ b/tests/components/PullRequestsTab.test.tsx @@ -784,5 +784,119 @@ describe("PullRequestsTab", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); }); + + it("hides Approve button when pr.checkStatus is 'failure'", () => { + setAllExpanded("pullRequests", true); + const onApprovePR = vi.fn(); + + const failingPR = makePullRequest({ + id: 14, + number: 14, + title: "Failing CI PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0014", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + render(() => ( + + )); + + expect(screen.queryByLabelText(/Approve #14/)).toBeNull(); + }); + + it("renders interactive DraftBadge button for self-authored draft PRs (in comfortable and compact density) and read-only span for another author's draft PR", () => { + setAllExpanded("pullRequests", true); + const onMarkPRReady = vi.fn(); + + const ownDraftPR = makePullRequest({ + id: 20, + number: 20, + title: "My Draft PR", + repoFullName: "org/repo", + userLogin: "alice", + nodeId: "PR_kwDOtest0020", + draft: true, + enriched: true, + }); + const otherDraftPR = makePullRequest({ + id: 21, + number: 21, + title: "Bob Draft PR", + repoFullName: "org/repo", + userLogin: "bob", + reviewerLogins: ["alice"], + nodeId: "PR_kwDOtest0021", + draft: true, + enriched: true, + }); + + const { unmount } = render(() => ( + + )); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #20 My Draft PR ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const otherSpan = badges.find((el) => el !== ownBtn)!; + expect(otherSpan.tagName.toLowerCase()).toBe("span"); + expect(otherSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + unmount(); + + // Compact density + onMarkPRReady.mockClear(); + setConfig("viewDensity", "compact"); + render(() => ( + + )); + + const compactBadges = screen.getAllByTestId("draft-badge"); + expect(compactBadges).toHaveLength(2); + + const compactOwnBtn = screen.getByLabelText("Mark #20 My Draft PR ready for review") as HTMLButtonElement; + expect(compactOwnBtn.tagName.toLowerCase()).toBe("button"); + expect(compactOwnBtn.textContent).toBe("D"); + + const compactOtherSpan = compactBadges.find((el) => el !== compactOwnBtn)!; + expect(compactOtherSpan.tagName.toLowerCase()).toBe("span"); + expect(compactOtherSpan.textContent).toBe("D"); + + fireEvent.click(compactOwnBtn); + expect(compactOwnBtn.textContent).toBe("Ready?"); + expect(onMarkPRReady).not.toHaveBeenCalled(); + + fireEvent.click(compactOwnBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + }); }); }); diff --git a/tests/components/dashboard/DependenciesTab.test.tsx b/tests/components/dashboard/DependenciesTab.test.tsx index 2d3dfc89..4bf19de2 100644 --- a/tests/components/dashboard/DependenciesTab.test.tsx +++ b/tests/components/dashboard/DependenciesTab.test.tsx @@ -861,6 +861,166 @@ describe("DependenciesTab — auto-merge badge and Approve action", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligibleDepPR); }); + + it("hides Approve button when pr.checkStatus is 'failure'", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const onApprovePR = vi.fn(); + const failingDepPR = makeNeedsActionPR({ + id: 8012, + number: 812, + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8012", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + renderTab({ + pullRequests: [failingDepPR], + userLogin: "testuser", + onApprovePR, + }); + + expect(screen.queryByLabelText(/^Approve #812 /)).toBeNull(); + }); + + it("renders interactive DraftBadge button for self-authored draft PRs in 'Needs Action' and invokes onMarkPRReady(pr) on second click", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const onMarkPRReady = vi.fn(); + const selfDraftDepPR = makeNeedsActionPR({ + id: 8020, + number: 820, + userLogin: "testuser", + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8020", + draft: true, + checkStatus: "success", + enriched: true, + }); + const botDraftDepPR = makeNeedsActionPR({ + id: 8021, + number: 821, + userLogin: "dependabot[bot]", + title: "Bump lodash from 4.17.20 to 4.17.21", + nodeId: "PR_kwDOdep8021", + draft: true, + checkStatus: "success", + enriched: true, + }); + + renderTab({ + pullRequests: [selfDraftDepPR, botDraftDepPR], + userLogin: "testuser", + onMarkPRReady, + }); + + const needsActionGroup = document.getElementById("dep-group-needs-action")!; + expect(needsActionGroup).not.toBeNull(); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #820 axios: 0.27.2 → 1.0.0 ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const botSpan = badges.find((el) => el !== ownBtn)!; + expect(botSpan.tagName.toLowerCase()).toBe("span"); + expect(botSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(selfDraftDepPR); + }); + + it("renders 'Merge conflict', 'Failing checks', and 'Checks running' badges in 'Needs Action' and links StatusDot to /checks", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const conflictPR = makeNeedsActionPR({ + id: 8030, + number: 830, + title: "Bump axios from 0.27.2 to 1.0.0", + htmlUrl: "https://github.com/owner/repo/pull/830", + checkStatus: "conflict", + enriched: true, + }); + const failingPR = makeNeedsActionPR({ + id: 8031, + number: 831, + title: "Bump lodash from 4.17.20 to 4.17.21", + htmlUrl: "https://github.com/owner/repo/pull/831", + checkStatus: "failure", + enriched: true, + }); + const pendingPR = makeNeedsActionPR({ + id: 8032, + number: 832, + title: "Bump react from 17.0.0 to 18.0.0", + htmlUrl: "https://github.com/owner/repo/pull/832", + checkStatus: "pending", + enriched: true, + }); + + renderTab({ + pullRequests: [conflictPR, failingPR, pendingPR], + userLogin: "testuser", + }); + + expect(screen.getByText("Merge conflict")).toBeDefined(); + expect(screen.getByText("Failing checks")).toBeDefined(); + expect(screen.getByText("Checks running")).toBeDefined(); + + const conflictDotLink = screen.getByLabelText("Checks blocked by merge conflict").closest("a"); + expect(conflictDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/830/checks"); + + const failingDotLink = screen.getByLabelText("Checks failing").closest("a"); + expect(failingDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/831/checks"); + + const pendingDotLink = screen.getByLabelText("Checks in progress").closest("a"); + expect(pendingDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/832/checks"); + }); + + it("classifies enriched non-draft PRs with checkStatus: null or reviewDecision: 'APPROVED' into 'Mergeable' and 'CHANGES_REQUESTED' into 'Needs Action'", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const noCiPR = makeMergeablePR({ + id: 8040, + number: 840, + title: "Bump axios from 0.27.1 to 0.27.2", + checkStatus: null, + reviewDecision: null, + }); + const approvedPR = makeMergeablePR({ + id: 8041, + number: 841, + title: "Bump lodash from 4.17.20 to 4.17.21", + checkStatus: "success", + reviewDecision: "APPROVED", + }); + const changesRequestedPR = makeNeedsActionPR({ + id: 8042, + number: 842, + title: "Bump react from 17.0.0 to 18.0.0", + checkStatus: "success", + reviewDecision: "CHANGES_REQUESTED", + }); + + renderTab({ + pullRequests: [noCiPR, approvedPR, changesRequestedPR], + userLogin: "testuser", + }); + + const mergeableGroup = document.getElementById("dep-group-mergeable")!; + expect(mergeableGroup.textContent).toContain("axios: 0.27.1 → 0.27.2"); + expect(mergeableGroup.textContent).toContain("lodash: 4.17.20 → 4.17.21"); + + const needsActionGroup = document.getElementById("dep-group-needs-action")!; + expect(needsActionGroup.textContent).toContain("react: 17.0.0 → 18.0.0"); + }); }); // ── Ignore button ───────────────────────────────────────────────────────────── diff --git a/tests/components/dashboard/TrackedTab.test.tsx b/tests/components/dashboard/TrackedTab.test.tsx index d0f417d9..27c03d17 100644 --- a/tests/components/dashboard/TrackedTab.test.tsx +++ b/tests/components/dashboard/TrackedTab.test.tsx @@ -451,4 +451,115 @@ describe("TrackedTab — auto-merge badge and Approve action", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); }); + + it("hides Approve button on tracked PR when pr.checkStatus is 'failure'", () => { + const onApprovePR = vi.fn(); + const failingPR = makePullRequest({ + id: 920, + number: 920, + title: "Failing Tracked PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack920", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 920, number: 920, type: "pullRequest", title: "Failing Tracked PR" }), + ], + }); + + render(() => ( + + )); + + expect(screen.queryByLabelText(/Approve #920/)).toBeNull(); + }); + + it("renders interactive DraftBadge button on live self-authored draft PR rows and invokes onMarkPRReady(pr) on confirmation", () => { + const onMarkPRReady = vi.fn(); + const ownDraftPR = makePullRequest({ + id: 930, + number: 930, + title: "My Tracked Draft PR", + userLogin: "testuser", + nodeId: "PR_kwDOtrack930", + draft: true, + enriched: true, + }); + const otherDraftPR = makePullRequest({ + id: 931, + number: 931, + title: "Other Tracked Draft PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack931", + draft: true, + enriched: true, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 930, number: 930, type: "pullRequest", title: "My Tracked Draft PR" }), + makeTrackedItem({ id: 931, number: 931, type: "pullRequest", title: "Other Tracked Draft PR" }), + ], + }); + + const { unmount } = render(() => ( + + )); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #930 My Tracked Draft PR ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const otherSpan = badges.find((el) => el !== ownBtn)!; + expect(otherSpan.tagName.toLowerCase()).toBe("span"); + expect(otherSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + unmount(); + + // Compact density + onMarkPRReady.mockClear(); + setConfig("viewDensity", "compact"); + render(() => ( + + )); + + const compactOwnBtn = screen.getByLabelText("Mark #930 My Tracked Draft PR ready for review") as HTMLButtonElement; + expect(compactOwnBtn.textContent).toBe("D"); + fireEvent.click(compactOwnBtn); + expect(compactOwnBtn.textContent).toBe("Ready?"); + fireEvent.click(compactOwnBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + }); }); diff --git a/tests/components/shared-badges.test.tsx b/tests/components/shared-badges.test.tsx index a65bc9e2..98bb5973 100644 --- a/tests/components/shared-badges.test.tsx +++ b/tests/components/shared-badges.test.tsx @@ -1,9 +1,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, fireEvent } from "@solidjs/testing-library"; +import { createSignal } from "solid-js"; import RoleBadge from "../../src/app/components/shared/RoleBadge"; import ReviewBadge from "../../src/app/components/shared/ReviewBadge"; import SizeBadge from "../../src/app/components/shared/SizeBadge"; import AutoMergeBadge from "../../src/app/components/shared/AutoMergeBadge"; +import DraftBadge from "../../src/app/components/shared/DraftBadge"; describe("RoleBadge", () => { it("renders nothing for empty roles", () => { @@ -199,3 +201,165 @@ describe("AutoMergeBadge", () => { vi.useRealTimers(); }); }); + +describe("DraftBadge", () => { + it("renders nothing when draft={false}", () => { + const { container } = render(() => ); + expect(container.textContent).toBe(""); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + }); + + it("renders read-only ('Draft' in comfortable, 'D' in compact) when onMarkReady is undefined", () => { + const { unmount } = render(() => ); + const comfortable = screen.getByTestId("draft-badge"); + expect(comfortable.tagName.toLowerCase()).toBe("span"); + expect(comfortable.textContent).toBe("Draft"); + expect(comfortable.className).toContain("badge-sm"); + unmount(); + + render(() => ); + const compact = screen.getByTestId("draft-badge"); + expect(compact.tagName.toLowerCase()).toBe("span"); + expect(compact.textContent).toBe("D"); + expect(compact.className).toContain("badge-xs"); + }); + + it("renders + + ); +} + +export default function DraftBadge(props: DraftBadgeProps) { return ( } > - - - + ); diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index f0e617eb..21212867 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -4512,6 +4512,24 @@ describe("DashboardPage — Mark PR ready integration", () => { }) ); + // 3b. Subsequent poll within 60s returning a non-null reviewDecision ("APPROVED") preserves + // "APPROVED" rather than overwriting it with entry.reviewDecision ("REVIEW_REQUIRED"), + // while still guarding pr.draft === false + capturedOnHotData!( + new Map([[77, { + state: "OPEN", + draft: true, + checkStatus: "success", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + }]]), + new Map(), + 0 + ); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByText("Review needed")).toBeNull(); + // 4. Advance Date.now past the 60_000ms TTL and run a full poll -> guard entry is evicted const expiredNow = Date.now() + 60_001; const nowSpy = vi.spyOn(Date, "now").mockReturnValue(expiredNow); @@ -4532,6 +4550,110 @@ describe("DashboardPage — Mark PR ready integration", () => { }); }); + it("merges Phase 2 draft state, reviewDecision, and recent ready guard when Phase 1 onLightData fires", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + markPullRequestReadyForReview: { + pullRequest: { + isDraft: false, + reviewDecision: "REVIEW_REQUIRED", + }, + }, + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-04-20T00:00:00Z" }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const lightPR1 = makePullRequest({ + id: 201, + number: 201, + title: "Phase 1 draft PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: true, + enriched: false, + nodeId: "PR_kwDOtest0201", + reviewDecision: null, + checkStatus: null, + }); + const lightPR2 = makePullRequest({ + id: 202, + number: 202, + title: "Mark ready during Phase 1", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: false, + nodeId: "PR_kwDOtest0202", + reviewDecision: null, + checkStatus: null, + }); + + let resolvePhase2!: (data: DashboardData) => void; + vi.mocked(pollService.fetchAllData).mockImplementation(async (onLightData) => { + onLightData?.({ issues: [], pullRequests: [lightPR1, lightPR2], workflowRuns: [], errors: [] }); + return new Promise((resolve) => { + resolvePhase2 = resolve; + }); + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + // Phase 1 is rendered; mark PR #202 ready before Phase 2 resolves + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #202 Mark ready during Phase 1 ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + await waitFor(() => expect(graphqlMock).toHaveBeenCalledOnce()); + + // Resolve Phase 2: PR #201 transitions draft: true -> false with reviewDecision: "CHANGES_REQUESTED", + // while PR #202 returns stale draft: true and reviewDecision: null that applyRecentReadyGuard must override + const enrichedPR1 = makePullRequest({ + id: 201, + number: 201, + title: "Phase 1 draft PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0201", + reviewDecision: "CHANGES_REQUESTED", + checkStatus: "success", + }); + const staleEnrichedPR2 = makePullRequest({ + id: 202, + number: 202, + title: "Mark ready during Phase 1", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0202", + reviewDecision: null, + checkStatus: "success", + }); + + resolvePhase2({ + issues: [], + pullRequests: [enrichedPR1, staleEnrichedPR2], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Changes")).toBeTruthy(); + expect(screen.getByText("Review needed")).toBeTruthy(); + }); + }); + it("handles 403 / FORBIDDEN error from markPullRequestReady by pushing mark-ready-pr: PAT permission notification without calling expireToken", async () => { const user = userEvent.setup(); const forbiddenErr = Object.assign(new Error("Resource not accessible by personal access token"), { @@ -4586,4 +4708,118 @@ describe("DashboardPage — Mark PR ready integration", () => { expect(btnAfter.disabled).toBe(false); expect(btnAfter.textContent).toBe("Draft"); }); + + it("treats 403 with rate-limit headers (x-ratelimit-remaining: 0 or retry-after) as a generic error instead of permission denied when marking PR ready", async () => { + const user = userEvent.setup(); + const rateLimit403 = Object.assign(new Error("API rate limit exceeded"), { + status: 403, + response: { headers: { "x-ratelimit-remaining": "0" } }, + }); + const retryAfter403 = Object.assign(new Error("Secondary rate limit"), { + status: 403, + response: { headers: { "retry-after": "60" } }, + }); + const graphqlMock = vi.fn() + .mockRejectedValueOnce(rateLimit403) + .mockRejectedValueOnce(retryAfter403); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [ + makePullRequest({ + id: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "mark-ready-pr:77", + "Failed to mark owner/repo#77 ready for review: API rate limit exceeded", + "error" + ); + }); + + // Second attempt: 403 with retry-after header + const retryBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(retryBtn); + await user.click(retryBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "mark-ready-pr:77", + "Failed to mark owner/repo#77 ready for review: Secondary rate limit", + "error" + ); + }); + }); + + it("handles 401 error when marking PR ready by calling expireToken and redirecting to /login", async () => { + const user = userEvent.setup(); + const unauthorizedErr = Object.assign(new Error("Bad credentials"), { status: 401 }); + const graphqlMock = vi.fn().mockRejectedValue(unauthorizedErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [ + makePullRequest({ + id: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + + await waitFor(() => { + expect(authStore.expireToken).toHaveBeenCalledOnce(); + expect(mockLocationReplace).toHaveBeenCalledWith("/login"); + }); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); + }); });