From 29a417f7c18b663c7ac9850a4882f2d3fcfc8d6c Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 07:22:29 -0400 Subject: [PATCH 1/8] feat(security): allow only validated PR approval mutation in Octokit write guard --- mcp/src/octokit.ts | 16 +++- mcp/tests/octokit.test.ts | 37 +++++++++ src/app/services/api-usage.ts | 3 +- src/app/services/github.ts | 50 +++++++++++-- src/shared/validation.ts | 17 +++++ tests/services/github.test.ts | 137 +++++++++++++++++++++++++++++++++- 6 files changed, 250 insertions(+), 10 deletions(-) diff --git a/mcp/src/octokit.ts b/mcp/src/octokit.ts index bd4d22f9..5b73bb34 100644 --- a/mcp/src/octokit.ts +++ b/mcp/src/octokit.ts @@ -11,6 +11,17 @@ type GitHubOctokitInstance = InstanceType; // ── Client factory ─────────────────────────────────────────────────────────── +function isReadOnlyGraphqlQuery(query: unknown): boolean { + if (typeof query !== "string") return false; + // Strip block strings, single-line strings, and # comments in a single left-to-right pass + const sanitized = query + .replace(/"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|#[^\r\n]*/g, (m) => (m.startsWith("#") ? "" : '""')) + .trim(); + if (!sanitized) return false; + if (!/^(?:query\b|\{)/i.test(sanitized)) return false; + return !/\b(?:mutation|subscription)\b/i.test(sanitized); +} + export function createOctokitClient(token: string): GitHubOctokitInstance { const client = new GitHubOctokit({ auth: token, @@ -46,12 +57,11 @@ export function createOctokitClient(token: string): GitHubOctokitInstance { }, }); - // Read-only guard: block any non-GET request except POST /graphql - // (GraphQL queries are read-only but always use POST). + // Read-only guard: block any non-GET request except read-only POST /graphql queries. client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; - if (method === "POST" && options.url === "/graphql") return; + if (method === "POST" && options.url === "/graphql" && isReadOnlyGraphqlQuery(options.query)) return; throw new Error( `[mcp] Write operation blocked: ${method} ${options.url}. This server is read-only.` ); diff --git a/mcp/tests/octokit.test.ts b/mcp/tests/octokit.test.ts index 6f6a0fae..1bf6c1a0 100644 --- a/mcp/tests/octokit.test.ts +++ b/mcp/tests/octokit.test.ts @@ -55,6 +55,43 @@ describe("createOctokitClient — write guard hook", () => { }) ).rejects.toThrow("Write operation blocked"); }); + + it("blocks GraphQL mutations (including addPullRequestReview) on POST /graphql", async () => { + const { createOctokitClient } = await import("../src/octokit.js"); + const client = createOctokitClient("fake-token"); + + await expect( + client.request("POST /graphql", { + query: `mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { state } + } + }`, + variables: { + pullRequestId: "PR_kwDOtest42", + commitOID: "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", + }, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `# query { viewer { login } }\nmutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `subscription { viewer { login } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── Singleton tests ─────────────────────────────────────────────────────────── diff --git a/src/app/services/api-usage.ts b/src/app/services/api-usage.ts index 33c82e24..b52a2878 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", "graphql", "rest", + "validateUser", "fetchOrgs", "fetchRepos", "rateLimitCheck", "approvePR", "graphql", "rest", ] as const; export type ApiCallSource = (typeof API_CALL_SOURCES)[number]; @@ -33,6 +33,7 @@ export const SOURCE_LABELS: Record = { fetchOrgs: "Fetch Orgs", fetchRepos: "Fetch Repos", rateLimitCheck: "Rate Limit Check", + approvePR: "Approve PR", graphql: "GraphQL (other)", rest: "REST (other)", }; diff --git a/src/app/services/github.ts b/src/app/services/github.ts index 0c6e4123..3d02c24f 100644 --- a/src/app/services/github.ts +++ b/src/app/services/github.ts @@ -6,6 +6,46 @@ 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 } from "../../shared/validation"; + +export { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE }; + +const NORMALIZED_APPROVE_MUTATION = APPROVE_PR_MUTATION.replace(/\s+/g, " "); + +function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown }): boolean { + if (typeof options.query !== "string") return false; + // Strip block strings, single-line strings, and # comments in a single left-to-right pass + const sanitized = options.query + .replace(/"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|#[^\r\n]*/g, (m) => (m.startsWith("#") ? "" : '""')) + .trim(); + if (!sanitized) return false; + + // 1. Allow read-only GraphQL queries (starts with `query` or `{` and has no top-level mutation/subscription) + if (/^(?:query\b|\{)/i.test(sanitized) && !/\b(?:mutation|subscription)\b/i.test(sanitized)) { + return true; + } + + // 2. Allow ONLY the exact canonical ApprovePullRequest mutation + 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.event !== undefined && vars.event !== "APPROVE") { + return false; + } + return true; +} // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -117,14 +157,14 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { }, }); - // Read-only guard: the OAuth App `repo` scope grants write access, but this - // app is strictly read-only. Block any non-GET request except POST /graphql - // (GraphQL queries are read-only but always use POST). + // 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). client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; - if (method === "POST" && options.url === "/graphql") return; - throw new Error(`[github] Write operation blocked: ${method} ${options.url}. This app is read-only.`); + 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.`); }); // Track every API request for usage analytics + update rate limit display diff --git a/src/shared/validation.ts b/src/shared/validation.ts index 5a8d62ec..e0c976a9 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -9,6 +9,23 @@ export const VALID_TRACKED_LOGIN = /^[A-Za-z0-9-]{1,39}(\[bot\])?$/; export const SEARCH_RESULT_CAP = 1000; +export const APPROVE_PR_MUTATION = ` + mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { + state + pullRequest { + reviewDecision + } + } + } + rateLimit { cost limit remaining resetAt } + } +`.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; + // ── Jira key detection ──────────────────────────────────────────────────────── const JIRA_KEY_REGEX = /\b([A-Z]{2,10}-\d+)\b/g; diff --git a/tests/services/github.test.ts b/tests/services/github.test.ts index c74d508a..ba00b185 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, type ApiRequestInfo } from "../../src/app/services/github"; +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 { clearCache } from "../../src/app/stores/cache"; // ── createGitHubClient ─────────────────────────────────────────────────────── @@ -91,6 +91,126 @@ describe("createGitHubClient", () => { }) ).rejects.toThrow(/Write operation blocked/); }); + + it("allows APPROVE_PR_MUTATION with valid PR_ nodeId and 40-hex commitOID", async () => { + const client = createGitHubClient("test-token"); + const mockFetch = vi.fn().mockImplementation(async () => + new Response( + JSON.stringify({ + data: { + addPullRequestReview: { + pullRequestReview: { state: "APPROVED", pullRequest: { reviewDecision: "APPROVED" } }, + }, + }, + }), + { status: 200, headers: { "content-type": "application/json" } } + ) + ); + vi.stubGlobal("fetch", mockFetch); + + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).resolves.toBeDefined(); + + // Also verify legacy Base64 node ID format via client.graphql() + await expect( + client.graphql(APPROVE_PR_MUTATION, { + pullRequestId: "MDExOlB1bGxSZXF1ZXN0NDI=", + commitOID: validSha, + }) + ).resolves.toBeDefined(); + + expect(GITHUB_NODE_ID_RE.test("PR_kwDOtest42")).toBe(true); + expect(GITHUB_NODE_ID_RE.test("MDExOlB1bGxSZXF1ZXN0NDI=")).toBe(true); + expect(GIT_SHA_RE.test(validSha)).toBe(true); + vi.unstubAllGlobals(); + }); + + it("blocks arbitrary, comment-prefixed, and aliased/combined GraphQL mutations", async () => { + const client = createGitHubClient("test-token"); + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { deleteIssue(input: { issueId: "I_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Comment-prefixed mutation + await expect( + client.request("POST /graphql", { + query: `# addPullRequestReview\nmutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Combined / aliased mutation smuggling + await expect( + client.request("POST /graphql", { + query: `mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + a: addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { state } + } + b: mergePullRequest(input: { pullRequestId: $pullRequestId }) { + clientMutationId + } + }`, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); + + it("blocks APPROVE_PR_MUTATION with missing or malformed pullRequestId or commitOID", async () => { + const client = createGitHubClient("test-token"); + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + // Missing variables object + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Malformed pullRequestId + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "bad!id", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Missing/non-SHA commitOID + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: "not-a-sha" }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Disallowed event override in variables + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha, event: "REQUEST_CHANGES" }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── cachedRequest ──────────────────────────────────────────────────────────── @@ -531,6 +651,21 @@ describe("hook.wrap — request tracking callbacks", () => { expect(cbSpy).not.toHaveBeenCalled(); }); + it("does not fire callback when GraphQL mutation guard blocks a mutation", async () => { + ensureRegistered(); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue( + new Response(JSON.stringify({}), { status: 200, headers: { "content-type": "application/json" } }) + )); + + const client = createGitHubClient("test-token"); + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + expect(cbSpy).not.toHaveBeenCalled(); + }); + it("fires callback exactly once per request even with multiple clients", async () => { ensureRegistered(); vi.stubGlobal("fetch", vi.fn().mockResolvedValue( From 7bc61b7d20e9bfa0fbae463a307f100f2df6cf1d Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 07:35:52 -0400 Subject: [PATCH 2/8] feat(api): add PR auto-merge and viewer review fields plus approvePullRequest mutation --- src/app/lib/format.ts | 2 +- src/app/services/api.ts | 145 +++++++++++++++++-- src/shared/format.ts | 20 +++ src/shared/types.ts | 9 ++ tests/helpers/factories.ts | 3 + tests/lib/format.test.ts | 136 ++++++++++++++++- tests/services/api-optimization.test.ts | 84 ++++++++++- tests/services/api.test.ts | 185 ++++++++++++++++++++++++ tests/services/hot-poll.test.ts | 43 ++++++ 9 files changed, 613 insertions(+), 14 deletions(-) diff --git a/src/app/lib/format.ts b/src/app/lib/format.ts index 04993943..a3a7dd2b 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 } from "../../shared/format"; +export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, canApprovePR } from "../../shared/format"; export function stripParenthetical(name: string): string { return name.replace(/\s*\(.*\)$/, ""); diff --git a/src/app/services/api.ts b/src/app/services/api.ts index b6def37b..755fc300 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -3,11 +3,11 @@ 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 } from "../../shared/validation"; -import type { Issue, IssueState, PullRequest, PullRequestState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; +import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; +import type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; // ── Re-exports from shared/types (backward compat for existing importers) ───── -export type { Issue, IssueState, PullRequest, PullRequestState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError, RateLimitInfo, DashboardSummary } from "../../shared/types"; +export type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError, RateLimitInfo, DashboardSummary } from "../../shared/types"; // ── Types ──────────────────────────────────────────────────────────────────── @@ -395,6 +395,9 @@ const HEAVY_PR_BACKFILL_QUERY = ` changedFiles comments { totalCount } reviewThreads { totalCount } + autoMergeRequest { mergeMethod } + viewerLatestReview { state } + viewerLatestReviewRequest { id } commits(last: 1) { nodes { commit { @@ -415,8 +418,12 @@ const HOT_PR_STATUS_QUERY = ` ... on PullRequest { databaseId state + headRefOid mergeStateStatus reviewDecision + autoMergeRequest { mergeMethod } + viewerLatestReview { state } + viewerLatestReviewRequest { id } commits(last: 1) { nodes { commit { @@ -433,8 +440,12 @@ const HOT_PR_STATUS_QUERY = ` interface HotPRStatusNode { databaseId: number; state: PullRequestState; + headRefOid?: string; mergeStateStatus: string; reviewDecision: string | null; + autoMergeRequest?: { mergeMethod: string } | null; + viewerLatestReview?: { state: string } | null; + viewerLatestReviewRequest?: { id: string } | null; commits: { nodes: { commit: { statusCheckRollup: { state: string } | null } }[] }; } @@ -477,6 +488,9 @@ interface GraphQLHeavyPRNode { changedFiles: number; comments: { totalCount: number }; reviewThreads: { totalCount: number }; + autoMergeRequest?: { mergeMethod: string } | null; + viewerLatestReview?: { state: string } | null; + viewerLatestReviewRequest?: { id: string } | null; commits: { nodes: { commit: { @@ -746,10 +760,16 @@ interface LightSearchResult { function processLightPRNode( node: GraphQLLightPRNode, prMap: Map, - nodeIdMap: Map + nodeIdMap: Map, + isViewerReviewRequested = false, ): boolean { if (node.databaseId == null || !node.repository) return false; - if (prMap.has(node.databaseId)) return false; + if (prMap.has(node.databaseId)) { + if (isViewerReviewRequested) { + prMap.get(node.databaseId)!.viewerReviewRequested = true; + } + return false; + } nodeIdMap.set(node.databaseId, node.id); prMap.set(node.databaseId, { @@ -778,6 +798,9 @@ function processLightPRNode( labels: node.labels.nodes.map((l) => ({ name: l.name, color: l.color })), reviewDecision: mapReviewDecision(node.reviewDecision), totalReviewCount: 0, + autoMergeMethod: null, + viewerReviewRequested: isViewerReviewRequested, + viewerLatestReviewState: null, starCount: node.repository.stargazerCount, enriched: false, nodeId: node.id, @@ -849,7 +872,7 @@ async function executeLightCombinedQuery( for (const node of response.prReviewReq.nodes) { if (prMap.size >= prCap) break; if (!node) continue; - processLightPRNode(node, prMap, nodeIdMap); + processLightPRNode(node, prMap, nodeIdMap, source === "lightSearch"); } if (isPartial) return; @@ -873,7 +896,7 @@ async function executeLightCombinedQuery( if (response.prReviewReq.pageInfo.hasNextPage && response.prReviewReq.pageInfo.endCursor && prMap.size < prCap) { prPaginationTasks.push(paginateGraphQLSearch( octokit, LIGHT_PR_SEARCH_QUERY, prRevQ, errorLabel, errors, - (node) => processLightPRNode(node, prMap, nodeIdMap), + (node) => processLightPRNode(node, prMap, nodeIdMap, source === "lightSearch"), () => prMap.size, prCap, source, response.prReviewReq.pageInfo.endCursor, )); } @@ -1077,6 +1100,9 @@ export interface PREnrichmentData { comments: number; reviewThreads: number; totalReviewCount: number; + autoMergeMethod: AutoMergeMethod | null; + viewerReviewRequested: boolean; + viewerLatestReviewState: ViewerReviewState | null; } /** @@ -1141,6 +1167,9 @@ export async function fetchPREnrichment( comments: node.comments.totalCount, reviewThreads: node.reviewThreads.totalCount, totalReviewCount: node.latestReviews.totalCount, + autoMergeMethod: mapAutoMergeMethod(node.autoMergeRequest?.mergeMethod), + viewerReviewRequested: Boolean(node.viewerLatestReviewRequest?.id), + viewerLatestReviewState: mapViewerReviewState(node.viewerLatestReview?.state), }); } } catch (err) { @@ -1347,6 +1376,9 @@ type EnrichmentFields = Pick< | "comments" | "reviewThreads" | "totalReviewCount" + | "autoMergeMethod" + | "viewerReviewRequested" + | "viewerLatestReviewState" >; /** Extracts just the heavy enrichment fields from any PR-shaped source. */ @@ -1362,6 +1394,9 @@ export function pickEnrichmentFields(source: EnrichmentFields): EnrichmentFields comments: source.comments, reviewThreads: source.reviewThreads, totalReviewCount: source.totalReviewCount, + autoMergeMethod: source.autoMergeMethod, + viewerReviewRequested: source.viewerReviewRequested, + viewerLatestReviewState: source.viewerLatestReviewState, }; } @@ -1372,7 +1407,8 @@ export function pickEnrichmentFields(source: EnrichmentFields): EnrichmentFields function mergeEnrichment( lightPRs: PullRequest[], enrichments: Map, - forkInfoMap: Map + forkInfoMap: Map, + viewerLogin = "", ): PullRequest[] { return lightPRs.map((pr) => { const e = enrichments.get(pr.id); @@ -1382,9 +1418,25 @@ function mergeEnrichment( forkInfoMap.set(pr.id, e.headRepository); } + const viewerLatestReviewState = e.viewerLatestReviewState; + const viewerReviewRequested = + viewerLatestReviewState === "APPROVED" && !e.viewerReviewRequested + ? false + : Boolean(pr.viewerReviewRequested || e.viewerReviewRequested); + const reviewerLogins = + viewerLogin && + (viewerReviewRequested || viewerLatestReviewState !== null) && + !e.reviewerLogins.includes(viewerLogin) + ? [...e.reviewerLogins, viewerLogin] + : e.reviewerLogins; + return { ...pr, ...pickEnrichmentFields(e), + reviewerLogins, + autoMergeMethod: e.autoMergeMethod, + viewerReviewRequested, + viewerLatestReviewState, enriched: true, }; }); @@ -1601,7 +1653,7 @@ export async function fetchIssuesAndPullRequests( // Apply main backfill enrichments to all PRs (main user PRs get enriched, tracked-only PRs get nothing yet) let enrichedPRs = mainBackfill.enrichments.size > 0 - ? mergeEnrichment(mergedPRs, mainBackfill.enrichments, forkInfoMap) + ? mergeEnrichment(mergedPRs, mainBackfill.enrichments, forkInfoMap, normalizedLogin) : mergedPRs; // Delta backfill: enrich PRs not already covered by main backfill — @@ -1617,7 +1669,7 @@ export async function fetchIssuesAndPullRequests( if (deltaNodeIds.length > 0) { const delta = await fetchPREnrichment(octokit, deltaNodeIds); backfillErrors.push(...delta.errors); - enrichedPRs = mergeEnrichment(enrichedPRs, delta.enrichments, forkInfoMap); + enrichedPRs = mergeEnrichment(enrichedPRs, delta.enrichments, forkInfoMap, normalizedLogin); } // Fork PR fallback for enriched PRs @@ -1672,6 +1724,24 @@ function mapReviewDecision( return null; } +function mapAutoMergeMethod(raw: string | null | undefined): AutoMergeMethod | null { + if (raw === "MERGE" || raw === "SQUASH" || raw === "REBASE") return raw; + return null; +} + +function mapViewerReviewState(raw: string | null | undefined): ViewerReviewState | null { + if ( + raw === "APPROVED" || + raw === "CHANGES_REQUESTED" || + raw === "COMMENTED" || + raw === "DISMISSED" || + raw === "PENDING" + ) { + return raw; + } + return null; +} + // ── Step 1: fetchOrgs ──────────────────────────────────────────────────────── /** @@ -1896,6 +1966,10 @@ export interface HotPRStatusUpdate { checkStatus: CheckStatus["status"]; mergeStateStatus: string; reviewDecision: PullRequest["reviewDecision"]; + headSha?: string; + autoMergeMethod?: AutoMergeMethod | null; + viewerReviewRequested?: boolean; + viewerLatestReviewState?: ViewerReviewState | null; } /** @@ -1932,6 +2006,10 @@ export async function fetchHotPRStatus( checkStatus, mergeStateStatus: node.mergeStateStatus, reviewDecision: mapReviewDecision(node.reviewDecision), + ...(node.headRefOid ? { headSha: node.headRefOid } : {}), + autoMergeMethod: mapAutoMergeMethod(node.autoMergeRequest?.mergeMethod), + viewerReviewRequested: Boolean(node.viewerLatestReviewRequest?.id), + viewerLatestReviewState: mapViewerReviewState(node.viewerLatestReview?.state), }); } })); @@ -2132,3 +2210,50 @@ export async function discoverUpstreamRepos( if (repos.length > CAP) repos.splice(CAP); return repos; } + +// ── PR Approval Mutation ───────────────────────────────────────────────────── + +interface ApprovePullRequestResponse { + addPullRequestReview: { + pullRequestReview: { + state: string | null; + pullRequest: { + reviewDecision: string | null; + } | null; + } | null; + } | null; + rateLimit?: GraphQLRateLimit; +} + +export async function approvePullRequest( + octokit: GitHubOctokit, + pullRequestId: string, + commitOID: string, +): Promise<{ state: ViewerReviewState | null; reviewDecision: PullRequest["reviewDecision"] }> { + if (!GITHUB_NODE_ID_RE.test(pullRequestId)) { + throw new Error(`Invalid pullRequestId: "${pullRequestId}"`); + } + if (!GIT_SHA_RE.test(commitOID)) { + throw new Error(`Invalid commitOID: "${commitOID}"`); + } + + const response = await octokit.graphql(APPROVE_PR_MUTATION, { + pullRequestId, + commitOID, + request: { apiSource: "approvePR", retries: 0 }, + }); + + if (response.rateLimit) { + updateGraphqlRateLimit(response.rateLimit); + } + + const review = response.addPullRequestReview?.pullRequestReview; + const state = mapViewerReviewState(review?.state); + if (state !== "APPROVED") { + throw new Error("GitHub did not confirm pull request approval"); + } + return { + state, + reviewDecision: mapReviewDecision(review?.pullRequest?.reviewDecision ?? null), + }; +} diff --git a/src/shared/format.ts b/src/shared/format.ts index 1dd8a7f4..d23f4f99 100644 --- a/src/shared/format.ts +++ b/src/shared/format.ts @@ -1,6 +1,8 @@ // ── Shared format utilities ─────────────────────────────────────────────────── // Browser-agnostic formatting functions shared between the SPA and MCP server. +import type { PullRequest } from "./types.js"; + const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); /** @@ -135,3 +137,21 @@ export function formatStarCount(count: number): string { if (count >= 1000) return `${parseFloat((count / 1000).toFixed(1))}k`; return String(count); } + +/** + * 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 + * - Authenticated user is not the PR author (case-insensitive) + * - Viewer has not already approved the PR without a fresh review request + * (`!(viewerLatestReviewState === "APPROVED" && !viewerReviewRequested)`) + * - Either branch protection requires review (`reviewDecision === "REVIEW_REQUIRED"`) + * or a review has been requested of the viewer/their team (`viewerReviewRequested === true`) + */ +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.userLogin.toLowerCase() === userLogin.toLowerCase()) return false; + if (pr.viewerLatestReviewState === "APPROVED" && !pr.viewerReviewRequested) return false; + return pr.reviewDecision === "REVIEW_REQUIRED" || pr.viewerReviewRequested === true; +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 5c5ce85a..2554f848 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -43,6 +43,9 @@ export interface CheckStatus { status: "success" | "failure" | "pending" | "conflict" | null; } +export type AutoMergeMethod = "MERGE" | "SQUASH" | "REBASE"; +export type ViewerReviewState = "APPROVED" | "CHANGES_REQUESTED" | "COMMENTED" | "DISMISSED" | "PENDING"; + export interface PullRequest { id: number; number: number; @@ -69,6 +72,12 @@ export interface PullRequest { labels: { name: string; color: string }[]; reviewDecision: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED" | null; totalReviewCount: number; + /** Non-null when GitHub auto-merge is enabled on the PR */ + autoMergeMethod?: AutoMergeMethod | null; + /** True when a review has been requested of the authenticated viewer (directly or via team) */ + viewerReviewRequested?: boolean; + /** State of the authenticated viewer's latest submitted review */ + viewerLatestReviewState?: ViewerReviewState | null; starCount?: number; /** False when only light fields are loaded (phase 1); true/undefined when fully enriched */ enriched?: boolean; diff --git a/tests/helpers/factories.ts b/tests/helpers/factories.ts index 3dd43590..f017026c 100644 --- a/tests/helpers/factories.ts +++ b/tests/helpers/factories.ts @@ -50,6 +50,9 @@ export function makePullRequest(overrides: Partial = {}): PullReque labels: [], reviewDecision: null, totalReviewCount: 0, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, enriched: true, ...overrides, }; diff --git a/tests/lib/format.test.ts b/tests/lib/format.test.ts index 42c251e4..e24b6a91 100644 --- a/tests/lib/format.test.ts +++ b/tests/lib/format.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary } from "../../src/app/lib/format"; +import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary, canApprovePR } from "../../src/app/lib/format"; +import { makePullRequest } from "../helpers/factories"; describe("relativeTime", () => { beforeEach(() => { @@ -444,3 +445,136 @@ describe("formatStarCount", () => { expect(formatStarCount(1234567)).toBe("1.2M"); }); }); + +describe("canApprovePR", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("returns true when reviewDecision is REVIEW_REQUIRED on an open enriched non-draft PR by another author", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(true); + }); + + it("returns true when viewerReviewRequested is true even if reviewDecision is null or CHANGES_REQUESTED", () => { + const prNullDecision = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: null, + viewerReviewRequested: true, + }); + const prChangesRequested = makePullRequest({ + nodeId: "PR_kwDOtest0002", + headSha: validSha, + userLogin: "author", + reviewDecision: "CHANGES_REQUESTED", + viewerReviewRequested: true, + }); + expect(canApprovePR(prNullDecision, "reviewer")).toBe(true); + expect(canApprovePR(prChangesRequested, "reviewer")).toBe(true); + }); + + it("returns false for self-authored PR (case-insensitive)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "OctoCat", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + }); + expect(canApprovePR(pr, "octocat")).toBe(false); + }); + + it("returns false when viewerLatestReviewState is APPROVED and viewerReviewRequested is false", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns true when viewerLatestReviewState is APPROVED but viewerReviewRequested is true (re-requested review)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: true, + }); + expect(canApprovePR(pr, "reviewer")).toBe(true); + }); + + it("returns false when PR is a draft", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + draft: true, + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns false when PR state is CLOSED or MERGED", () => { + const closedPr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + state: "CLOSED", + reviewDecision: "REVIEW_REQUIRED", + }); + const mergedPr = makePullRequest({ + nodeId: "PR_kwDOtest0002", + headSha: validSha, + userLogin: "author", + state: "MERGED", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(closedPr, "reviewer")).toBe(false); + expect(canApprovePR(mergedPr, "reviewer")).toBe(false); + }); + + it("returns false when PR is not yet enriched (enriched === false)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + enriched: false, + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns false when nodeId, headSha, or userLogin is missing", () => { + const noNodeId = makePullRequest({ + nodeId: undefined, + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + const noHeadSha = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: "", + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + const validPr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(noNodeId, "reviewer")).toBe(false); + expect(canApprovePR(noHeadSha, "reviewer")).toBe(false); + expect(canApprovePR(validPr, "")).toBe(false); + }); +}); diff --git a/tests/services/api-optimization.test.ts b/tests/services/api-optimization.test.ts index 674c39b2..c008c0c9 100644 --- a/tests/services/api-optimization.test.ts +++ b/tests/services/api-optimization.test.ts @@ -57,7 +57,7 @@ const graphqlLightPRNodeDefaults = { repository: { nameWithOwner: "octocat/Hello-World" }, headRefName: "feature-branch", baseRefName: "main", - reviewDecision: "APPROVED", + reviewDecision: "APPROVED" as string | null, labels: { nodes: [{ name: "feature", color: "a2eeef" }] }, }; @@ -69,7 +69,7 @@ function makeHeavyPRNode(databaseId: number, _nodeId?: string) { headRepository: { owner: { login: "octocat" }, nameWithOwner: "octocat/Hello-World" }, mergeStateStatus: "CLEAN", assignees: { nodes: [{ login: "octocat" }] }, - reviewRequests: { nodes: [{ requestedReviewer: { login: "reviewer2" } }] }, + reviewRequests: { nodes: [{ requestedReviewer: { login: "reviewer2" } as { login?: string } | null }] }, latestReviews: { totalCount: 1, nodes: [{ author: { login: "reviewer1" } }] }, additions: 100, deletions: 20, @@ -77,6 +77,9 @@ function makeHeavyPRNode(databaseId: number, _nodeId?: string) { comments: { totalCount: 3 }, reviewThreads: { totalCount: 2 }, commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + autoMergeRequest: null as { mergeMethod: string } | null, + viewerLatestReview: null as { state: string } | null, + viewerLatestReviewRequest: null as { id: string } | null, }; } @@ -708,6 +711,9 @@ describe("pickEnrichmentFields", () => { checkStatus: "success", additions: 10, reviewerLogins: ["r1"], + autoMergeMethod: "SQUASH", + viewerReviewRequested: true, + viewerLatestReviewState: "COMMENTED", }); const fields = pickEnrichmentFields(pr); expect(fields).toEqual({ @@ -721,9 +727,83 @@ describe("pickEnrichmentFields", () => { comments: pr.comments, reviewThreads: pr.reviewThreads, totalReviewCount: pr.totalReviewCount, + autoMergeMethod: pr.autoMergeMethod, + viewerReviewRequested: pr.viewerReviewRequested, + viewerLatestReviewState: pr.viewerLatestReviewState, }); expect(fields).not.toHaveProperty("title"); expect(fields).not.toHaveProperty("state"); expect(fields).not.toHaveProperty("enriched"); }); }); + +describe("Phase 1 prReviewReq -> Phase 2 mergeEnrichment team review request preservation", () => { + const repos = makeRepos(2); + + it("retains viewerReviewRequested: true and adds normalized userLogin to reviewerLogins for a team review request (even when also returned in prInvolves)", async () => { + const lightPR = makeLightPRNode({ + id: "PR_kwDOteam42", + databaseId: 42, + reviewDecision: null, + }); + const heavyNode = { + ...makeHeavyPRNode(42, "PR_kwDOteam42"), + // Team review request: no direct User node in reviewRequests and viewerLatestReviewRequest is null + reviewRequests: { nodes: [{ requestedReviewer: {} }] }, + latestReviews: { totalCount: 0, nodes: [] }, + autoMergeRequest: { mergeMethod: "SQUASH" }, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + }; + + const octokit = makeTwoPhaseOctokit( + async () => ({ + issues: makeSearchResponse([]), + prInvolves: makeSearchResponse([lightPR]), + prReviewReq: makeSearchResponse([lightPR]), + rateLimit, + }), + [heavyNode], + ); + + const result = await fetchIssuesAndPullRequests(octokit as unknown as OctokitLike, repos, "TestUser"); + expect(result.pullRequests).toHaveLength(1); + const pr = result.pullRequests[0]; + expect(pr.viewerReviewRequested).toBe(true); + expect(pr.autoMergeMethod).toBe("SQUASH"); + expect(pr.reviewerLogins).toContain("testuser"); + }); + + it("clears viewerReviewRequested to false when viewerLatestReview.state is APPROVED and viewerLatestReviewRequest is null, while retaining userLogin in reviewerLogins", async () => { + const lightPR = makeLightPRNode({ + id: "PR_kwDOteam43", + databaseId: 43, + reviewDecision: "APPROVED", + }); + const heavyNode = { + ...makeHeavyPRNode(43, "PR_kwDOteam43"), + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + autoMergeRequest: null, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: null, + }; + + const octokit = makeTwoPhaseOctokit( + async () => ({ + issues: makeSearchResponse([]), + prInvolves: makeSearchResponse([]), + prReviewReq: makeSearchResponse([lightPR]), + rateLimit, + }), + [heavyNode], + ); + + const result = await fetchIssuesAndPullRequests(octokit as unknown as OctokitLike, repos, "TestUser"); + expect(result.pullRequests).toHaveLength(1); + const pr = result.pullRequests[0]; + expect(pr.viewerLatestReviewState).toBe("APPROVED"); + expect(pr.viewerReviewRequested).toBe(false); + expect(pr.reviewerLogins).toContain("testuser"); + }); +}); diff --git a/tests/services/api.test.ts b/tests/services/api.test.ts index cbdfd562..1cda4863 100644 --- a/tests/services/api.test.ts +++ b/tests/services/api.test.ts @@ -7,8 +7,10 @@ import { validateGitHubUser, fetchPREnrichment, fetchHotPRStatus, + approvePullRequest, type RepoRef, } from "../../src/app/services/api"; +import { APPROVE_PR_MUTATION } from "../../src/app/services/github"; import { clearCache } from "../../src/app/stores/cache"; import { pushNotification } from "../../src/app/lib/errors"; @@ -1279,3 +1281,186 @@ describe("error-path rateLimit extraction — updateGraphqlRateLimit called", () ); }); }); + +// ── fetchPREnrichment — autoMergeMethod, viewerLatestReviewState, viewerReviewRequested ── + +describe("fetchPREnrichment — autoMergeMethod and viewer review fields", () => { + it("maps MERGE, SQUASH, REBASE, unknown autoMergeMethod, viewerLatestReviewState, and viewerReviewRequested", async () => { + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + nodes: [ + { + databaseId: 101, + headRefOid: "1111111111111111111111111111111111111111", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 1, nodes: [] }, + additions: 10, + deletions: 2, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + autoMergeRequest: { mergeMethod: "SQUASH" }, + viewerLatestReview: { state: "CHANGES_REQUESTED" }, + viewerLatestReviewRequest: { id: "RR_kwDOtest101" }, + }, + { + databaseId: 102, + headRefOid: "2222222222222222222222222222222222222222", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "MERGE" }, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: null, + }, + { + databaseId: 103, + headRefOid: "3333333333333333333333333333333333333333", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "REBASE" }, + viewerLatestReview: { state: "UNKNOWN_STATE" }, + viewerLatestReviewRequest: null, + }, + { + databaseId: 104, + headRefOid: "4444444444444444444444444444444444444444", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "INVALID" }, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + }, + ], + rateLimit: { limit: 5000, remaining: 4990, resetAt: "2026-04-23T12:00:00Z" }, + }) + ); + + const { enrichments } = await fetchPREnrichment(octokit as never, ["PR_1", "PR_2", "PR_3", "PR_4"]); + + expect(enrichments.get(101)).toMatchObject({ + autoMergeMethod: "SQUASH", + viewerLatestReviewState: "CHANGES_REQUESTED", + viewerReviewRequested: true, + }); + expect(enrichments.get(102)).toMatchObject({ + autoMergeMethod: "MERGE", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + }); + expect(enrichments.get(103)).toMatchObject({ + autoMergeMethod: "REBASE", + viewerLatestReviewState: null, + viewerReviewRequested: false, + }); + expect(enrichments.get(104)).toMatchObject({ + autoMergeMethod: null, + viewerLatestReviewState: null, + viewerReviewRequested: false, + }); + }); +}); + +// ── approvePullRequest ──────────────────────────────────────────────────────── + +describe("approvePullRequest", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("executes APPROVE_PR_MUTATION with commitOID, retries: 0, updates rateLimit, and returns normalized state + reviewDecision", async () => { + const githubModule = await import("../../src/app/services/github"); + const updateSpy = vi.spyOn(githubModule, "updateGraphqlRateLimit"); + + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { + reviewDecision: "APPROVED", + }, + }, + }, + rateLimit: { cost: 1, limit: 5000, remaining: 4988, resetAt: "2026-04-23T12:00:00Z" }, + }) + ); + + const result = await approvePullRequest(octokit as never, "PR_kwDOtest0042", validSha); + + expect(octokit.graphql).toHaveBeenCalledWith(APPROVE_PR_MUTATION, { + pullRequestId: "PR_kwDOtest0042", + commitOID: validSha, + request: { apiSource: "approvePR", retries: 0 }, + }); + expect(updateSpy).toHaveBeenCalledWith( + expect.objectContaining({ limit: 5000, remaining: 4988, resetAt: "2026-04-23T12:00:00Z" }) + ); + expect(result).toEqual({ + state: "APPROVED", + reviewDecision: "APPROVED", + }); + }); + + it("rejects invalid pullRequestId or commitOID before calling octokit.graphql", async () => { + const octokit = makeOctokit(async () => ({ data: {} })); + + await expect( + approvePullRequest(octokit as never, "bad!id", validSha) + ).rejects.toThrow(/Invalid pullRequestId/); + + await expect( + approvePullRequest(octokit as never, "PR_kwDOtest0042", "not-a-40-char-sha") + ).rejects.toThrow(/Invalid commitOID/); + + expect(octokit.graphql).not.toHaveBeenCalled(); + }); + + it("throws when GitHub response does not confirm APPROVED review state", async () => { + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + addPullRequestReview: { + pullRequestReview: { + state: "PENDING", + pullRequest: { reviewDecision: "REVIEW_REQUIRED" }, + }, + }, + }) + ); + + await expect( + approvePullRequest(octokit as never, "PR_kwDOtest0042", validSha) + ).rejects.toThrow("GitHub did not confirm pull request approval"); + }); +}); diff --git a/tests/services/hot-poll.test.ts b/tests/services/hot-poll.test.ts index c82b25d0..a5d351e4 100644 --- a/tests/services/hot-poll.test.ts +++ b/tests/services/hot-poll.test.ts @@ -204,6 +204,49 @@ describe("fetchHotPRStatus", () => { const { results } = await fetchHotPRStatus(octokit as never, ["PR_node4"]); expect(results.get(45)!.checkStatus).toBe("pending"); }); + + it("maps headRefOid (headSha), autoMergeMethod, viewerLatestReviewState, and viewerReviewRequested", async () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + const octokit = makeOctokit(undefined, () => Promise.resolve({ + nodes: [ + { + databaseId: 46, + state: "OPEN", + mergeStateStatus: "CLEAN", + reviewDecision: "REVIEW_REQUIRED", + headRefOid: validSha, + autoMergeRequest: { mergeMethod: "REBASE" }, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: { id: "RR_kwDOtest46" }, + commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + }, + { + databaseId: 47, + state: "OPEN", + mergeStateStatus: "CLEAN", + reviewDecision: null, + autoMergeRequest: null, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + commits: { nodes: [] }, + }, + ], + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-01-01T00:00:00Z" }, + })); + + const { results } = await fetchHotPRStatus(octokit as never, ["PR_node5", "PR_node6"]); + const u46 = results.get(46)!; + expect(u46.headSha).toBe(validSha); + expect(u46.autoMergeMethod).toBe("REBASE"); + expect(u46.viewerLatestReviewState).toBe("APPROVED"); + expect(u46.viewerReviewRequested).toBe(true); + + const u47 = results.get(47)!; + expect(u47.headSha).toBeUndefined(); + expect(u47.autoMergeMethod).toBeNull(); + expect(u47.viewerLatestReviewState).toBeNull(); + expect(u47.viewerReviewRequested).toBe(false); + }); }); describe("fetchWorkflowRunById", () => { From e174f93f74fa9ce705f1a6807664769cf441ed39 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 07:44:40 -0400 Subject: [PATCH 3/8] feat(ui): add AutoMergeBadge and two-step inline Approve button on PR rows --- .../components/dashboard/DependenciesTab.tsx | 14 ++ src/app/components/dashboard/ItemRow.tsx | 119 +++++++++++++++- .../components/dashboard/PullRequestsTab.tsx | 10 +- src/app/components/dashboard/TrackedTab.tsx | 10 +- src/app/components/shared/AutoMergeBadge.tsx | 26 ++++ tests/components/ItemRow.test.tsx | 98 ++++++++++++++ tests/components/PullRequestsTab.test.tsx | 128 +++++++++++++++++- .../components/dashboard/TrackedTab.test.tsx | 102 ++++++++++++++ tests/components/shared-badges.test.tsx | 50 +++++++ 9 files changed, 551 insertions(+), 6 deletions(-) create mode 100644 src/app/components/shared/AutoMergeBadge.tsx diff --git a/src/app/components/dashboard/DependenciesTab.tsx b/src/app/components/dashboard/DependenciesTab.tsx index 00158b3a..b1487975 100644 --- a/src/app/components/dashboard/DependenciesTab.tsx +++ b/src/app/components/dashboard/DependenciesTab.tsx @@ -3,6 +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 type { PullRequest } from "../../services/api"; import type { AbandonedDependency } from "../../lib/dependency-dashboard"; import { @@ -23,6 +24,7 @@ import RepoGroupHeader from "../shared/RepoGroupHeader"; import StatusDot from "../shared/StatusDot"; import SizeBadge from "../shared/SizeBadge"; import ReviewBadge from "../shared/ReviewBadge"; +import AutoMergeBadge from "../shared/AutoMergeBadge"; import ItemRow from "./ItemRow"; import SkeletonRows from "../shared/SkeletonRows"; @@ -110,6 +112,8 @@ interface DependenciesTabProps { userLogin: string; trackedBotLogins: ReadonlySet; onRefresh?: () => void; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } export default function DependenciesTab(props: DependenciesTabProps) { @@ -363,6 +367,9 @@ export default function DependenciesTab(props: DependenciesTabProps) { enableTracking={config.enableTracking} onIgnore={handleIgnore} onTrack={handleTrack} + userLogin={props.userLogin} + onApprovePR={props.onApprovePR} + approvingPRIds={props.approvingPRIds} /> )} @@ -385,6 +392,9 @@ interface StatusGroupProps { enableTracking: boolean; onIgnore: (pr: PullRequest) => void; onTrack: (pr: PullRequest) => void; + userLogin: string; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } function stripCommitPrefix(title: string): string { @@ -436,6 +446,9 @@ function StatusGroup(props: StatusGroupProps) { onIgnore={() => props.onIgnore(pr)} onTrack={props.enableTracking ? () => props.onTrack(pr) : undefined} isTracked={props.enableTracking ? props.trackedPrIds.has(pr.id) : undefined} + onApprove={props.onApprovePR && canApprovePR(pr, props.userLogin) ? () => props.onApprovePR!(pr) : undefined} + isApproving={props.approvingPRIds?.has(pr.id)} + approveAutoMerge={pr.autoMergeMethod != null} isPolling={props.hotPollingPRIds?.has(pr.id)} hideAuthor hideNumber @@ -455,6 +468,7 @@ function StatusGroup(props: StatusGroupProps) { + 0 || pr.deletions > 0)}> diff --git a/src/app/components/dashboard/ItemRow.tsx b/src/app/components/dashboard/ItemRow.tsx index 07f8ccbf..a8d3bbe8 100644 --- a/src/app/components/dashboard/ItemRow.tsx +++ b/src/app/components/dashboard/ItemRow.tsx @@ -1,4 +1,4 @@ -import { createMemo, For, JSX, Show } from "solid-js"; +import { createEffect, createMemo, createSignal, For, JSX, onCleanup, Show } from "solid-js"; import { config } from "../../stores/config"; import { isSafeGitHubUrl } from "../../lib/url"; import { relativeTime, shortRelativeTime, formatCount } from "../../lib/format"; @@ -20,6 +20,12 @@ export interface ItemRowProps { onIgnore?: () => void; onTrack?: () => void; isTracked?: boolean; + /** Callback invoked on the second (confirmation) click of the Approve button */ + onApprove?: () => void; + /** True while an approval mutation for this PR is in flight */ + isApproving?: boolean; + /** True when auto-merge is enabled on the PR, adding an auto-merge hint on the Confirm step */ + approveAutoMerge?: boolean; commentCount?: number; hideRepo?: boolean; hideAuthor?: boolean; @@ -35,6 +41,57 @@ export default function ItemRow(props: ItemRowProps) { const isCompact = createMemo(() => config.viewDensity === "compact"); const safeUrl = () => isSafeGitHubUrl(props.url) ? props.url : undefined; + const APPROVE_CONFIRM_TIMEOUT_MS = 4_000; + const [confirmingApprove, setConfirmingApprove] = createSignal(false); + let approveConfirmTimer: ReturnType | undefined; + + function clearApproveTimer() { + if (approveConfirmTimer !== undefined) { + clearTimeout(approveConfirmTimer); + approveConfirmTimer = undefined; + } + } + + function resetApproveConfirm() { + clearApproveTimer(); + setConfirmingApprove(false); + } + + createEffect(() => { + if (!props.onApprove || props.isApproving) { + resetApproveConfirm(); + } + }); + + onCleanup(() => { + clearApproveTimer(); + }); + + function handleApproveClick(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + if (props.isApproving || !props.onApprove) return; + if (!confirmingApprove()) { + setConfirmingApprove(true); + clearApproveTimer(); + approveConfirmTimer = setTimeout(() => { + approveConfirmTimer = undefined; + setConfirmingApprove(false); + }, APPROVE_CONFIRM_TIMEOUT_MS); + return; + } + resetApproveConfirm(); + props.onApprove(); + } + + function handleApproveKeyDown(e: KeyboardEvent) { + if (e.key === "Escape" && confirmingApprove()) { + e.stopPropagation(); + e.preventDefault(); + resetApproveConfirm(); + } + } + // Static date info — recomputed only when createdAt/updatedAt change (not on tick) const staticDateInfo = createMemo(() => { const createdTitle = `Created: ${new Date(props.createdAt).toLocaleString()}`; @@ -299,6 +356,66 @@ export default function ItemRow(props: ItemRowProps) { + {/* Approve button — two-step inline confirmation for eligible PRs */} + + + + + + {/* Pin button — visible on hover, always visible when tracked */} diff --git a/src/app/components/dashboard/PullRequestsTab.tsx b/src/app/components/dashboard/PullRequestsTab.tsx index 6b8298d6..8e44d9c2 100644 --- a/src/app/components/dashboard/PullRequestsTab.tsx +++ b/src/app/components/dashboard/PullRequestsTab.tsx @@ -4,7 +4,7 @@ import { viewState, ignoreItem, unignoreItem, toggleExpandedRepo, setAllExpanded import { createTabFilterHandlers, mergeActiveFilters } from "../../lib/tabFilters"; import { isPrVisible } from "../../lib/filters"; import type { PullRequest, RepoRef } from "../../services/api"; -import { deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; import { isSafeGitHubUrl } from "../../lib/url"; import ExpandCollapseButtons from "../shared/ExpandCollapseButtons"; import ItemRow from "./ItemRow"; @@ -15,6 +15,7 @@ import PaginationControls from "../shared/PaginationControls"; import { scopeFilterGroup, prFilterGroups, type FilterChipGroupDef } from "../shared/filterTypes"; import FilterToolbar from "../shared/FilterToolbar"; import ReviewBadge from "../shared/ReviewBadge"; +import AutoMergeBadge from "../shared/AutoMergeBadge"; import SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import SkeletonRows from "../shared/SkeletonRows"; @@ -43,6 +44,8 @@ export interface PullRequestsTabProps { filterPreset?: Record; jiraKeyMap?: () => ReadonlyMap; depPrIds?: ReadonlySet; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } type SortField = "repo" | "title" | "author" | "createdAt" | "updatedAt" | "checkStatus" | "reviewDecision" | "size"; @@ -523,6 +526,9 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { onIgnore={() => handleIgnore(pr)} onTrack={config.enableTracking ? () => handleTrack(pr) : undefined} isTracked={config.enableTracking ? trackedPrIds().has(pr.id) : undefined} + onApprove={props.onApprovePR && canApprovePR(pr, props.userLogin) ? () => props.onApprovePR!(pr) : undefined} + isApproving={props.approvingPRIds?.has(pr.id)} + approveAutoMerge={pr.autoMergeMethod != null} surfacedByBadge={ props.trackedUsers && props.trackedUsers.length > 0 ? + @@ -576,6 +583,7 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { + diff --git a/src/app/components/dashboard/TrackedTab.tsx b/src/app/components/dashboard/TrackedTab.tsx index f48191c0..d1301896 100644 --- a/src/app/components/dashboard/TrackedTab.tsx +++ b/src/app/components/dashboard/TrackedTab.tsx @@ -3,11 +3,12 @@ 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 { deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, 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 SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import { Tooltip } from "../shared/Tooltip"; @@ -76,6 +77,8 @@ export interface TrackedTabProps { refreshTick?: number; userLogin: string; hotPollingPRIds?: ReadonlySet; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } export default function TrackedTab(props: TrackedTabProps) { @@ -248,6 +251,9 @@ export default function TrackedTab(props: TrackedTabProps) { commentCount={commentCount()} onTrack={() => untrackItem(item.id, item.type as "issue" | "pullRequest")} isTracked={true} + onApprove={pr() && props.onApprovePR && canApprovePR(pr()!, props.userLogin) ? () => props.onApprovePR!(pr()!) : undefined} + isApproving={item.type === "pullRequest" && props.approvingPRIds?.has(item.id)} + approveAutoMerge={pr()?.autoMergeMethod != null} isPolling={item.type === "pullRequest" && props.hotPollingPRIds?.has(item.id)} > + @@ -295,6 +302,7 @@ export default function TrackedTab(props: TrackedTabProps) { + diff --git a/src/app/components/shared/AutoMergeBadge.tsx b/src/app/components/shared/AutoMergeBadge.tsx new file mode 100644 index 00000000..0a1377e3 --- /dev/null +++ b/src/app/components/shared/AutoMergeBadge.tsx @@ -0,0 +1,26 @@ +import { Show } from "solid-js"; +import type { AutoMergeMethod } from "../../services/api"; +import { Tooltip } from "./Tooltip"; + +export interface AutoMergeBadgeProps { + method?: AutoMergeMethod | null; + compact?: boolean; +} + +export default function AutoMergeBadge(props: AutoMergeBadgeProps) { + return ( + + {(method) => ( + + + auto + + + )} + + ); +} diff --git a/tests/components/ItemRow.test.tsx b/tests/components/ItemRow.test.tsx index d9c43b4c..741cc6bd 100644 --- a/tests/components/ItemRow.test.tsx +++ b/tests/components/ItemRow.test.tsx @@ -475,4 +475,102 @@ describe("ItemRow", () => { // updatedAt was 30m before MOCK_NOW; after +3h it is 3h30m ago → Math.floor(210/60) = 3 → "3h" expect(updated!.textContent).toBe("3h"); }); + + describe("Approve button (two-step inline confirmation)", () => { + it("is omitted when onApprove is undefined and rendered when onApprove is provided", () => { + const { unmount } = render(() => ); + expect(screen.queryByLabelText(/Approve #42/i)).toBeNull(); + unmount(); + + render(() => ); + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + expect(btn.textContent).toContain("Approve"); + }); + + it("Click 1 transitions from 'Approve' to 'Confirm?' without calling onApprove", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + + expect(onApprove).not.toHaveBeenCalled(); + expect(btn.textContent).toBe("Confirm?"); + expect(btn.getAttribute("aria-label")).toBe("Confirm approve #42 Fix a bug"); + }); + + it("shows 'Confirm (auto)' and auto-merge aria-label when approveAutoMerge={true}", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + + expect(onApprove).not.toHaveBeenCalled(); + expect(btn.textContent).toBe("Confirm (auto)"); + expect(btn.getAttribute("aria-label")).toBe("Confirm approve #42 Fix a bug (auto-merge enabled)"); + }); + + it("auto-resets from 'Confirm?' back to 'Approve' after 4000ms without calling onApprove", () => { + vi.useFakeTimers(); + const onApprove = vi.fn(); + const { unmount } = render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + vi.advanceTimersByTime(4000); + expect(btn.textContent).toContain("Approve"); + expect(btn.getAttribute("aria-label")).toBe("Approve #42 Fix a bug"); + expect(onApprove).not.toHaveBeenCalled(); + + unmount(); + vi.useRealTimers(); + }); + + it("resets immediately on Escape keyDown or blur while in 'Confirm?' state", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + fireEvent.keyDown(btn, { key: "Escape" }); + expect(btn.textContent).toContain("Approve"); + + // Re-arm and test blur reset + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + fireEvent.blur(btn); + expect(btn.textContent).toContain("Approve"); + expect(onApprove).not.toHaveBeenCalled(); + }); + + it("Click 2 while in 'Confirm?' state invokes onApprove once and resets confirmation state", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + fireEvent.click(btn); + expect(onApprove).toHaveBeenCalledOnce(); + expect(btn.textContent).toContain("Approve"); + }); + + it("disables button, shows .loading-spinner, and ignores clicks when isApproving={true}", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approving #42 Fix a bug") as HTMLButtonElement; + expect(btn.disabled).toBe(true); + expect(btn.querySelector(".loading-spinner")).not.toBeNull(); + + fireEvent.click(btn); + expect(onApprove).not.toHaveBeenCalled(); + }); + }); }); diff --git a/tests/components/PullRequestsTab.test.tsx b/tests/components/PullRequestsTab.test.tsx index 67b2017d..22a7de99 100644 --- a/tests/components/PullRequestsTab.test.tsx +++ b/tests/components/PullRequestsTab.test.tsx @@ -1,5 +1,5 @@ -import { describe, it, expect, beforeEach } from "vitest"; -import { render, screen } from "@solidjs/testing-library"; +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent } from "@solidjs/testing-library"; import userEvent from "@testing-library/user-event"; import { createSignal } from "solid-js"; import PullRequestsTab from "../../src/app/components/dashboard/PullRequestsTab"; @@ -7,7 +7,7 @@ import type { PullRequest } from "../../src/app/services/api"; import * as viewStore from "../../src/app/stores/view"; import { setAllExpanded } from "../../src/app/stores/view"; import { makePullRequest, resetViewStore } from "../helpers/index"; -import { updateConfig, resetConfig } from "../../src/app/stores/config"; +import { setConfig, updateConfig, resetConfig } from "../../src/app/stores/config"; beforeEach(() => { resetViewStore(); @@ -663,4 +663,126 @@ describe("PullRequestsTab", () => { const rows = container.querySelectorAll("[role='listitem']"); expect(rows[0]?.querySelector(".animate-shimmer")).toBeFalsy(); }); + + describe("auto-merge badge and inline Approve button", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge in comfortable and compact density when autoMergeMethod is set, and hides when null or unenriched", () => { + setAllExpanded("pullRequests", true); + const prAuto = makePullRequest({ + id: 1, + number: 1, + title: "Auto PR", + repoFullName: "org/repo", + autoMergeMethod: "SQUASH", + enriched: true, + }); + const prUnenriched = makePullRequest({ + id: 2, + number: 2, + title: "Unenriched PR", + repoFullName: "org/repo", + autoMergeMethod: "SQUASH", + enriched: false, + }); + const prNoAuto = makePullRequest({ + id: 3, + number: 3, + title: "Manual PR", + repoFullName: "org/repo", + autoMergeMethod: null, + enriched: true, + }); + + const { unmount } = render(() => ( + + )); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + unmount(); + + setConfig("viewDensity", "compact"); + render(() => ( + + )); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("shows Approve button only for eligible PRs and invokes onApprovePR(pr) on two-step confirmation", () => { + setAllExpanded("pullRequests", true); + const onApprovePR = vi.fn(); + + const eligiblePR = makePullRequest({ + id: 10, + number: 10, + title: "Needs Review PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0010", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const selfPR = makePullRequest({ + id: 11, + number: 11, + title: "Self PR", + repoFullName: "org/repo", + userLogin: "alice", + nodeId: "PR_kwDOtest0011", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const alreadyApprovedPR = makePullRequest({ + id: 12, + number: 12, + title: "Already Approved PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0012", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + enriched: true, + }); + const draftPR = makePullRequest({ + id: 13, + number: 13, + title: "Draft PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0013", + headSha: validSha, + draft: true, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + + render(() => ( + + )); + + const approveBtn = screen.getByLabelText("Approve #10 Needs Review PR"); + expect(screen.queryByLabelText(/Approve #11/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #12/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #13/)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); + }); + }); }); diff --git a/tests/components/dashboard/TrackedTab.test.tsx b/tests/components/dashboard/TrackedTab.test.tsx index a2f649a8..d0f417d9 100644 --- a/tests/components/dashboard/TrackedTab.test.tsx +++ b/tests/components/dashboard/TrackedTab.test.tsx @@ -30,6 +30,7 @@ vi.mock("../../../src/app/lib/url", () => ({ import TrackedTab from "../../../src/app/components/dashboard/TrackedTab"; import { viewState, resetViewState, updateViewState, untrackJiraItem } from "../../../src/app/stores/view"; +import { setConfig, resetConfig } from "../../../src/app/stores/config"; // ── Setup ───────────────────────────────────────────────────────────────────── @@ -37,6 +38,7 @@ beforeEach(() => { vi.clearAllMocks(); localStorageMock.clear(); resetViewState(); + resetConfig(); }); // ── Tests ───────────────────────────────────────────────────────────────────── @@ -350,3 +352,103 @@ describe("TrackedTab — Jira items", () => { expect(screen.queryByText(/#-42/)).toBeNull(); }); }); + +describe("TrackedTab — auto-merge badge and Approve action", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge on live PR rows in comfortable and compact density, and omits when null or unenriched", () => { + const prAuto = makePullRequest({ + id: 901, + number: 901, + title: "Auto Tracked PR", + autoMergeMethod: "MERGE", + enriched: true, + }); + const prUnenriched = makePullRequest({ + id: 902, + number: 902, + title: "Unenriched Tracked PR", + autoMergeMethod: "MERGE", + enriched: false, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 901, number: 901, type: "pullRequest", title: "Auto Tracked PR" }), + makeTrackedItem({ id: 902, number: 902, type: "pullRequest", title: "Unenriched Tracked PR" }), + ], + }); + + const { unmount } = render(() => ( + + )); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + unmount(); + + setConfig("viewDensity", "compact"); + render(() => ( + + )); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("renders Approve button on eligible live PR rows, suppresses on issue/fallback/self-authored rows, and calls onApprovePR(pr) on confirmation", () => { + const onApprovePR = vi.fn(); + const eligiblePR = makePullRequest({ + id: 910, + number: 910, + title: "Eligible Tracked PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack910", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const selfPR = makePullRequest({ + id: 911, + number: 911, + title: "Self Tracked PR", + userLogin: "testuser", + nodeId: "PR_kwDOtrack911", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const liveIssue = makeIssue({ id: 912, number: 912, title: "Tracked Issue" }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 910, number: 910, type: "pullRequest", title: "Eligible Tracked PR" }), + makeTrackedItem({ id: 911, number: 911, type: "pullRequest", title: "Self Tracked PR" }), + makeTrackedItem({ id: 912, number: 912, type: "issue", title: "Tracked Issue" }), + makeTrackedItem({ id: 913, number: 913, type: "pullRequest", title: "Fallback Missing PR" }), + ], + }); + + render(() => ( + + )); + + const approveBtn = screen.getByLabelText("Approve #910 Eligible Tracked PR"); + expect(screen.queryByLabelText(/Approve #911/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #912/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #913/)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); + }); +}); diff --git a/tests/components/shared-badges.test.tsx b/tests/components/shared-badges.test.tsx index fcc0a286..a65bc9e2 100644 --- a/tests/components/shared-badges.test.tsx +++ b/tests/components/shared-badges.test.tsx @@ -3,6 +3,7 @@ import { render, screen, fireEvent } from "@solidjs/testing-library"; 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"; describe("RoleBadge", () => { it("renders nothing for empty roles", () => { @@ -149,3 +150,52 @@ describe("SizeBadge", () => { }); }); }); + +describe("AutoMergeBadge", () => { + it("renders nothing when method is null or undefined", () => { + const { container: c1 } = render(() => ); + expect(c1.textContent).toBe(""); + const { container: c2 } = render(() => ); + expect(c2.textContent).toBe(""); + }); + + it("renders 'auto' with badge-sm by default for MERGE, SQUASH, and REBASE", () => { + const { unmount: u1 } = render(() => ); + const b1 = screen.getByTestId("auto-merge-badge"); + expect(b1.textContent).toBe("auto"); + expect(b1.className).toContain("badge-sm"); + expect(b1.getAttribute("aria-label")).toBe("Auto-merge enabled (merge)"); + u1(); + + const { unmount: u2 } = render(() => ); + const b2 = screen.getByTestId("auto-merge-badge"); + expect(b2.getAttribute("aria-label")).toBe("Auto-merge enabled (squash)"); + u2(); + + const { unmount: u3 } = render(() => ); + const b3 = screen.getByTestId("auto-merge-badge"); + expect(b3.getAttribute("aria-label")).toBe("Auto-merge enabled (rebase)"); + u3(); + }); + + it("renders badge-xs when compact={true}", () => { + render(() => ); + const badge = screen.getByTestId("auto-merge-badge"); + expect(badge.className).toContain("badge-xs"); + expect(badge.className).not.toContain("badge-sm"); + }); + + it("shows tooltip with merge method on hover", () => { + vi.useFakeTimers(); + const { container, unmount } = render(() => ); + const trigger = container.querySelector("span.inline-flex"); + expect(trigger).not.toBeNull(); + fireEvent.pointerEnter(trigger!); + vi.advanceTimersByTime(300); + expect(document.body.textContent).toContain("Auto-merge enabled (squash)"); + fireEvent.pointerLeave(trigger!); + vi.advanceTimersByTime(500); + unmount(); + vi.useRealTimers(); + }); +}); From a86ef531053ba0540a0a14c7acde0fc58dc438a8 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 08:01:22 -0400 Subject: [PATCH 4/8] feat(dashboard): wire PR approval mutation, optimistic state, and error handling --- .../components/dashboard/DashboardPage.tsx | 239 ++++++++++++++++-- tests/components/DashboardPage.test.tsx | 237 ++++++++++++++++- .../dashboard/DashboardPage.test.tsx | 88 ++++++- 3 files changed, 545 insertions(+), 19 deletions(-) diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index f86006de..96811238 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -14,7 +14,7 @@ import DependenciesTab from "./DependenciesTab"; import { isDependencyPr, expandBotLogins, needsBodyFallback, parseRenovateBody, type VersionInfo } from "../../lib/dependency-detection"; import { isRepoExcludedFromDependencies } from "../../lib/dependency-exclusion"; import { findDashboardIssues, parseAbandonedSection, resetAbandonedPatternCache, type AbandonedDependency } from "../../lib/dependency-dashboard"; -import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields } from "../../services/api"; +import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields, approvePullRequest } from "../../services/api"; import type { SortOption } from "../shared/SortDropdown"; import type { Issue, PullRequest, WorkflowRun } from "../../services/api"; import { fetchOrgs } from "../../services/api"; @@ -36,10 +36,10 @@ import { JIRA_SETTINGS_ACTION, type JiraIssue } from "../../../shared/jira-types import { detectAndLookupJiraKeys } from "../../services/jira-keys"; import JiraAssignedTab from "./JiraAssignedTab"; import { updateRelaySnapshot } from "../../lib/mcp-relay"; -import { pushNotification, pushError } from "../../lib/errors"; +import { pushNotification, pushError, dismissNotificationBySource } from "../../lib/errors"; import { detectNewItems, dispatchNotifications } from "../../lib/notifications"; import { getClient, getGraphqlRateLimit, fetchRateLimitDetails } from "../../services/github"; -import { formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; +import { canApprovePR, formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; import { setsEqual } from "../../lib/collections"; import { withScrollLock } from "../../lib/scroll"; import { Tooltip } from "../shared/Tooltip"; @@ -179,6 +179,38 @@ const [depMeta, setDepMeta] = createSignal>(loa let _fetchingDashboardBodies = false; let _fetchingDepBodies = false; +const [approvingPRIds, setApprovingPRIds] = createSignal>(new Set()); +const RECENT_APPROVAL_TTL_MS = 60_000; +const recentlyApprovedPRs = new Map< + number, + { headSha: string; reviewDecision: PullRequest["reviewDecision"]; approvedAt: number } +>(); + +function applyRecentApprovalGuard(pr: PullRequest, currentLogin: string): void { + const now = Date.now(); + for (const [id, entry] of recentlyApprovedPRs) { + if (now - entry.approvedAt > RECENT_APPROVAL_TTL_MS) { + recentlyApprovedPRs.delete(id); + } + } + const entry = recentlyApprovedPRs.get(pr.id); + if (!entry) return; + if (pr.headSha && pr.headSha !== entry.headSha) { + recentlyApprovedPRs.delete(pr.id); + return; + } + // Keep the entry for the full 60s TTL even if Phase 2 `nodes()` already shows + // `viewerLatestReviewState === "APPROVED"`, because Phase 1's search index can lag + // behind `nodes()` on `reviewDecision` ("REVIEW_REQUIRED" / "CHANGES_REQUESTED" vs "APPROVED"). + pr.viewerLatestReviewState = "APPROVED"; + pr.viewerReviewRequested = false; + pr.reviewDecision = entry.reviewDecision; + const loginLower = currentLogin.toLowerCase(); + if (loginLower && !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower)) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } +} + // Skip retrying a dep-PR body fetch that errored/timed out on its last attempt until // this cooldown elapses — prevents burning a full GRAPHQL_BODY_FETCH_TIMEOUT_MS timeout, // an undeduped Sentry event, and a repeated user notification every poll cycle for as @@ -201,6 +233,8 @@ onAuthCleared(() => { _fetchingDashboardBodies = false; _fetchingDepBodies = false; _depBodyFailureCooldown.clear(); + setApprovingPRIds(new Set()); + recentlyApprovedPRs.clear(); resetAbandonedPatternCache(); const coord = _coordinator(); if (coord) { @@ -260,6 +294,8 @@ async function pollFetch(): Promise { setHasFetchedFresh(true); const now = new Date(); + const currentLogin = user()?.login ?? ""; + for (const pr of data.pullRequests) applyRecentApprovalGuard(pr, currentLogin); if (phaseOneFired) { // Phase 1 fired — use fine-grained merge for the light→enriched @@ -291,11 +327,16 @@ async function pollFetch(): Promise { const regressing = e.enriched === false && pr.enriched !== false; if (!regressing) { Object.assign(pr, pickEnrichmentFields(e)); + pr.reviewDecision = e.reviewDecision; + pr.autoMergeMethod = e.autoMergeMethod; + pr.viewerReviewRequested = e.viewerReviewRequested; + pr.viewerLatestReviewState = e.viewerLatestReviewState; pr.enriched = e.enriched; } pr.nodeId = e.nodeId; pr.surfacedBy = e.surfacedBy; pr.starCount = e.starCount; + applyRecentApprovalGuard(pr, currentLogin); } } else { state.pullRequests = fallbackToPreviousEnrichment(state.pullRequests, data.pullRequests); @@ -391,6 +432,7 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void if (oldSb) { pr.surfacedBy = [...new Set([...(pr.surfacedBy ?? []), ...oldSb])]; } + applyRecentApprovalGuard(pr, user()?.login ?? ""); } withScrollLock(() => { @@ -745,6 +787,8 @@ export default function DashboardPage() { if (s === "CLOSED" || s === "MERGED") terminalPrIds.add(prId); } setDashboardData(produce((state) => { + const currentLogin = user()?.login ?? ""; + const loginLower = currentLogin.toLowerCase(); // Apply PR status updates for (const pr of state.pullRequests) { const update = prUpdates.get(pr.id); @@ -752,6 +796,30 @@ export default function DashboardPage() { pr.state = update.state; // detect closed/merged quickly pr.checkStatus = update.checkStatus; pr.reviewDecision = update.reviewDecision; + if (update.headSha) { + pr.headSha = update.headSha; + } + if (update.autoMergeMethod !== undefined) { + pr.autoMergeMethod = update.autoMergeMethod; + } + if (update.viewerLatestReviewState !== undefined) { + pr.viewerLatestReviewState = update.viewerLatestReviewState; + } + if (update.viewerReviewRequested !== undefined) { + if (update.viewerReviewRequested) { + pr.viewerReviewRequested = true; + } else if (update.viewerLatestReviewState === "APPROVED") { + pr.viewerReviewRequested = false; + } + } + if ( + loginLower && + (pr.viewerReviewRequested || pr.viewerLatestReviewState != null) && + !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower) + ) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } + applyRecentApprovalGuard(pr, currentLogin); } // Apply workflow run updates for (const run of state.workflowRuns) { @@ -1335,6 +1403,149 @@ export default function DashboardPage() { [...new Set([...config.selectedRepos, ...config.upstreamRepos, ...config.monitoredRepos].map(r => r.fullName))] ); + function isPermissionDeniedError(err: unknown): boolean { + if (!err || typeof err !== "object") return false; + const errObj = err as Record; + if (Array.isArray(errObj.errors)) { + for (const item of errObj.errors) { + if (item && typeof item === "object") { + const type = (item as Record).type; + const msg = String((item as Record).message ?? ""); + if ( + type === "FORBIDDEN" || + type === "INSUFFICIENT_SCOPES" || + /resource not accessible by personal access token|insufficient_scopes|write access/i.test(msg) + ) { + return true; + } + } + } + } + if (errObj.status === 403) { + const headers = (errObj.response as { headers?: Record } | undefined)?.headers; + if (headers?.["x-ratelimit-remaining"] === "0" || headers?.["retry-after"]) return false; + return true; + } + return false; + } + + function isStaleCommitError(err: unknown): boolean { + if (!err || typeof err !== "object") return false; + const errObj = err as Record; + const msg = err instanceof Error ? err.message : String(errObj.message ?? ""); + return /commitOID|was not part of the pull request|pull request head|outdated|end of the branch/i.test(msg); + } + + async function handleApprovePR(pr: PullRequest): Promise { + const currentLogin = userLogin(); + if (!canApprovePR(pr, currentLogin)) return; + if (approvingPRIds().has(pr.id)) return; + const client = getClient(); + if (!client || !pr.nodeId || !pr.headSha) return; + + // Clear any prior notification for this PR so a retry with the same error message + // is not suppressed by pushNotification's same-message no-op guard. + dismissNotificationBySource(`approve-pr:${pr.id}`); + + setApprovingPRIds((prev) => { + const next = new Set(prev); + next.add(pr.id); + return next; + }); + + try { + const result = await approvePullRequest(client, pr.nodeId, pr.headSha); + if (getClient() !== client) return; + + const nextDecision: PullRequest["reviewDecision"] = + result.reviewDecision ?? (pr.reviewDecision === "REVIEW_REQUIRED" ? "APPROVED" : pr.reviewDecision); + + recentlyApprovedPRs.set(pr.id, { + headSha: pr.headSha, + reviewDecision: nextDecision, + approvedAt: Date.now(), + }); + + setDashboardData( + produce((state) => { + const target = state.pullRequests.find((item) => item.id === pr.id); + if (!target) return; + target.viewerLatestReviewState = "APPROVED"; + target.viewerReviewRequested = false; + target.reviewDecision = nextDecision; + const loginLower = currentLogin.toLowerCase(); + if (loginLower && !target.reviewerLogins.some((r) => r.toLowerCase() === loginLower)) { + target.reviewerLogins = [...target.reviewerLogins, loginLower]; + } + }) + ); + + // Seed the approved PR into _hotPRs so the next hot-poll cycle detects if + // GitHub auto-merged it (splicing it from dashboardData.pullRequests via onHotData), + // even when checkStatus was already "success" prior to approval. + seedHotSetsFromTargeted({ + issues: [], + pullRequests: [{ ...pr, enriched: true, checkStatus: "pending" }], + workflowRuns: [], + errors: [], + }); + + const snapshot = { + _v: CACHE_VERSION, + issues: [...dashboardData.issues], + pullRequests: [...dashboardData.pullRequests], + workflowRuns: [...dashboardData.workflowRuns], + lastRefreshedAt: dashboardData.lastRefreshedAt?.toISOString() ?? null, + }; + setTimeout(() => { + try { + localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); + } catch { + // Non-fatal + } + }, 0); + + pushNotification(`approve-pr:${pr.id}`, `Approved ${pr.repoFullName}#${pr.number}`, "info"); + } catch (err) { + if (getClient() !== client) return; + const status = + typeof err === "object" && err !== null && typeof (err as Record).status === "number" + ? ((err as Record).status as number) + : null; + if (status === 401) { + expireToken(); + window.location.replace("/login"); + return; + } + if (isPermissionDeniedError(err)) { + pushNotification( + `approve-pr:${pr.id}`, + "Unable to approve PR: your token lacks Pull Requests write permission. For fine-grained PATs, set 'Pull requests' to 'Read and write' in GitHub Settings, then replace your token in Settings.", + "error" + ); + return; + } + if (isStaleCommitError(err)) { + pushNotification( + `approve-pr:${pr.id}`, + `Could not approve ${pr.repoFullName}#${pr.number}: new commits were pushed — refreshing`, + "warning" + ); + _coordinator()?.manualRefresh(); + return; + } + const message = err instanceof Error ? err.message : "Unknown error"; + pushNotification(`approve-pr:${pr.id}`, `Failed to approve ${pr.repoFullName}#${pr.number}: ${message}`, "error"); + } finally { + setApprovingPRIds((prev) => { + if (!prev.has(pr.id)) return prev; + const next = new Set(prev); + next.delete(pr.id); + return next; + }); + } + } + return (
@@ -1405,6 +1616,8 @@ export default function DashboardPage() { refreshTick={refreshTick()} jiraKeyMap={jiraKeyMap} depPrIds={dependencyPrIds()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1420,20 +1633,8 @@ export default function DashboardPage() { userLogin={userLogin()} trackedBotLogins={trackedBotLogins()} onRefresh={() => _coordinator()?.manualRefresh()} - /> - - - _coordinator()?.manualRefresh()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1444,6 +1645,8 @@ export default function DashboardPage() { refreshTick={refreshTick()} userLogin={userLogin()} hotPollingPRIds={hotPollingPRIds()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1508,6 +1711,8 @@ export default function DashboardPage() { customTabId={tab().id} filterPreset={tab().filterPreset} jiraKeyMap={jiraKeyMap} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index 691b5cff..3dcfcad3 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -6,6 +6,7 @@ import { makeIssue, makePullRequest, makeWorkflowRun } from "../helpers/index"; import type { DashboardData } from "../../src/app/services/poll"; import type { HotPRStatusUpdate, HotWorkflowRunUpdate } from "../../src/app/services/api"; import { GRAPHQL_BODY_FETCH_TIMEOUT_MS } from "../../src/app/services/api"; +import { APPROVE_PR_MUTATION } from "../../src/shared/validation"; const mockLocationReplace = vi.fn(); @@ -59,11 +60,12 @@ vi.mock("../../src/app/services/jira-keys", () => ({ clearJiraKeyCache: vi.fn(), })); -// Mock github service (used by Header + DashboardPage org sync) +// Mock github service (used by Header + DashboardPage org sync + approvePullRequest) vi.mock("../../src/app/services/github", () => ({ getCoreRateLimit: () => null, getGraphqlRateLimit: () => null, getClient: vi.fn(() => null), + updateGraphqlRateLimit: vi.fn(), })); // Mock notifications lib @@ -111,6 +113,8 @@ let pollService: typeof import("../../src/app/services/poll"); let authStore: typeof import("../../src/app/stores/auth"); let viewStore: typeof import("../../src/app/stores/view"); let configStore: typeof import("../../src/app/stores/config"); +let githubService: typeof import("../../src/app/services/github"); +let errorsLib: typeof import("../../src/app/lib/errors"); beforeEach(async () => { // Clear localStorage so loadCachedDashboard doesn't pick up stale data from prior tests @@ -172,6 +176,8 @@ beforeEach(async () => { authStore = await import("../../src/app/stores/auth"); viewStore = await import("../../src/app/stores/view"); configStore = await import("../../src/app/stores/config"); + githubService = await import("../../src/app/services/github"); + errorsLib = await import("../../src/app/lib/errors"); mockLocationReplace.mockClear(); capturedFetchAll = null; @@ -179,6 +185,10 @@ beforeEach(async () => { capturedOnTargetedData = null; vi.mocked(authStore.clearAuth).mockClear(); vi.mocked(authStore.expireToken).mockClear(); + vi.mocked(githubService.getClient).mockReset(); + vi.mocked(githubService.getClient).mockReturnValue(null); + vi.mocked(errorsLib.pushNotification).mockClear(); + vi.mocked(errorsLib.dismissNotificationBySource).mockClear(); vi.mocked(pollService.fetchAllData).mockResolvedValue({ issues: [], pullRequests: [], @@ -3452,3 +3462,228 @@ describe("DashboardPage — Jira expiration UX and reactive re-authentication", expect(screen.queryByText("Expired")).toBeNull(); }); }); + +// ── PR Approval Integration ────────────────────────────────────────────────── + +describe("DashboardPage — PR approval integration", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("completes two-step PR approval flow, updates badge to Approved, seeds hot sets, and pushes info notification", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { + reviewDecision: "APPROVED", + }, + }, + }, + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-04-20T00:00:00Z" }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + await waitFor(() => { + expect(screen.getByText("Review needed")).toBeTruthy(); + }); + + const approveBtn = screen.getByLabelText("Approve #42 Fix race condition"); + expect(approveBtn.textContent).toBe("Approve"); + + // Step 1: Enter confirmation mode + await user.click(approveBtn); + expect(graphqlMock).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + // Step 2: Confirm approval + await user.click(approveBtn); + await waitFor(() => { + expect(graphqlMock).toHaveBeenCalledOnce(); + }); + + expect(graphqlMock).toHaveBeenCalledWith(APPROVE_PR_MUTATION, { + pullRequestId: "PR_kwDOtest0042", + commitOID: validSha, + request: { apiSource: "approvePR", retries: 0 }, + }); + + expect(errorsLib.dismissNotificationBySource).toHaveBeenCalledWith("approve-pr:42"); + expect(pollService.seedHotSetsFromTargeted).toHaveBeenCalledWith({ + issues: [], + pullRequests: [expect.objectContaining({ id: 42, enriched: true, checkStatus: "pending" })], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByText("Review needed")).toBeNull(); + }); + expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); + + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Approved owner/repo#42", + "info" + ); + }); + + it("handles 403 / FORBIDDEN error without calling expireToken, leaves PR unapproved, re-enables Approve button, and pushes PAT write permission error", async () => { + const user = userEvent.setup(); + const forbiddenErr = Object.assign(new Error("Resource not accessible by personal access token"), { + status: 403, + errors: [{ type: "FORBIDDEN", message: "Resource not accessible by personal access token" }], + }); + const graphqlMock = vi.fn().mockRejectedValue(forbiddenErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition") as HTMLButtonElement); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Unable to approve PR: your token lacks Pull Requests write permission. For fine-grained PATs, set 'Pull requests' to 'Read and write' in GitHub Settings, then replace your token in Settings.", + "error" + ); + }); + + expect(authStore.expireToken).not.toHaveBeenCalled(); + expect(screen.getByText("Review needed")).toBeTruthy(); + + const btnAfter = screen.getByLabelText("Approve #42 Fix race condition") as HTMLButtonElement; + expect(btnAfter.disabled).toBe(false); + expect(btnAfter.textContent).toBe("Approve"); + }); + + it("handles stale commitOID error by pushing a warning notification and triggering manualRefresh", async () => { + const user = userEvent.setup(); + const manualRefreshSpy = vi.fn(); + vi.mocked(pollService.createPollCoordinator).mockImplementation( + (_getInterval: unknown, fetchAll: () => Promise) => { + capturedFetchAll = fetchAll; + void fetchAll().catch(() => {}); + return { + isRefreshing: () => false, + lastRefreshAt: () => null, + manualRefresh: manualRefreshSpy, + destroy: vi.fn(), + }; + } + ); + + const staleErr = new Error("Pull request review thread commitOID was not part of the pull request"); + const graphqlMock = vi.fn().mockRejectedValue(staleErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Could not approve owner/repo#42: new commits were pushed — refreshing", + "warning" + ); + }); + expect(manualRefreshSpy).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/components/dashboard/DashboardPage.test.tsx b/tests/components/dashboard/DashboardPage.test.tsx index 4bd8363d..80691671 100644 --- a/tests/components/dashboard/DashboardPage.test.tsx +++ b/tests/components/dashboard/DashboardPage.test.tsx @@ -55,13 +55,17 @@ describe("hot poll terminal PR splice logic", () => { labels: [], reviewDecision: null, totalReviewCount: 0, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, enriched: true, }; } function simulateHotPollCallback( state: { pullRequests: PullRequest[] }, - prUpdates: Map + prUpdates: Map, + currentLogin = "" ): void { // Mirrors the onHotData callback logic in DashboardPage.tsx (without SolidJS store produce) const terminalPrIds = new Set(); @@ -70,12 +74,36 @@ describe("hot poll terminal PR splice logic", () => { terminalPrIds.add(prId); } } + const loginLower = currentLogin.toLowerCase(); for (const pr of state.pullRequests) { const update = prUpdates.get(pr.id); if (!update) continue; pr.state = update.state; pr.checkStatus = update.checkStatus; pr.reviewDecision = update.reviewDecision; + if (update.headSha) { + pr.headSha = update.headSha; + } + if (update.autoMergeMethod !== undefined) { + pr.autoMergeMethod = update.autoMergeMethod; + } + if (update.viewerLatestReviewState !== undefined) { + pr.viewerLatestReviewState = update.viewerLatestReviewState; + } + if (update.viewerReviewRequested !== undefined) { + if (update.viewerReviewRequested) { + pr.viewerReviewRequested = true; + } else if (update.viewerLatestReviewState === "APPROVED") { + pr.viewerReviewRequested = false; + } + } + if ( + loginLower && + (pr.viewerReviewRequested || pr.viewerLatestReviewState != null) && + !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower) + ) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } } if (terminalPrIds.size > 0) { state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); @@ -130,4 +158,62 @@ describe("hot poll terminal PR splice logic", () => { expect(state.pullRequests.map((p) => p.id)).toEqual([100, 102]); }); + + it("updates headSha and autoMergeMethod while preserving Phase 1 team viewerReviewRequested and reviewerLogins until approved", () => { + const teamRequestedPR: PullRequest = { + ...makeOpenPR(7), + viewerReviewRequested: true, + reviewerLogins: [], + }; + const state = { pullRequests: [teamRequestedPR] }; + const newSha = "f0e1d2c3b4a5f0e1d2c3b4a5f0e1d2c3b4a5f0e1"; + + // Hot poll returns direct viewerReviewRequested: false (because review was requested via a team), + // updated headSha, and autoMergeMethod: "SQUASH", while viewer has not yet approved. + const prUpdates1 = new Map([ + [ + 7, + { + state: "OPEN", + checkStatus: "success", + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED", + headSha: newSha, + autoMergeMethod: "SQUASH", + viewerReviewRequested: false, + viewerLatestReviewState: null, + }, + ], + ]); + + simulateHotPollCallback(state, prUpdates1, "TestUser"); + + expect(state.pullRequests[0].headSha).toBe(newSha); + expect(state.pullRequests[0].autoMergeMethod).toBe("SQUASH"); + expect(state.pullRequests[0].viewerReviewRequested).toBe(true); + expect(state.pullRequests[0].reviewerLogins).toEqual(["testuser"]); + + // Subsequent hot poll after viewer approves: viewerReviewRequested is cleared and viewer remains in reviewerLogins + const prUpdates2 = new Map([ + [ + 7, + { + state: "OPEN", + checkStatus: "success", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + headSha: newSha, + autoMergeMethod: "SQUASH", + viewerReviewRequested: false, + viewerLatestReviewState: "APPROVED", + }, + ], + ]); + + simulateHotPollCallback(state, prUpdates2, "TestUser"); + + expect(state.pullRequests[0].viewerLatestReviewState).toBe("APPROVED"); + expect(state.pullRequests[0].viewerReviewRequested).toBe(false); + expect(state.pullRequests[0].reviewerLogins).toEqual(["testuser"]); + }); }); From 6bc6e0a3fd40d516917476d4dfb5c00a76897c50 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 08:19:56 -0400 Subject: [PATCH 5/8] docs: document PR auto-merge badge, inline PR approval, and least-privilege write guard --- DEPLOY.md | 2 +- README.md | 8 +- docs/USER_GUIDE.md | 20 ++++- src/app/pages/LoginPage.tsx | 2 +- src/app/pages/PrivacyPage.tsx | 8 +- tests/components/LoginPage.test.tsx | 7 ++ .../dashboard/DependenciesTab.test.tsx | 81 +++++++++++++++++++ 7 files changed, 117 insertions(+), 11 deletions(-) diff --git a/DEPLOY.md b/DEPLOY.md index 7a8dd5d2..a721a68e 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -132,7 +132,7 @@ The login flow requests `scope=repo read:org`: | `repo` | Read issues, PRs, check runs, workflow runs (includes private repos) | | `read:org` | `GET /user/orgs` — list user's organizations for the org selector | -**Note:** The `repo` scope grants write access to repositories, but this app never performs write operations (POST/PUT/PATCH/DELETE on repo endpoints). It is read-only by design. +**Note:** The `repo` scope grants write access to repositories. An Octokit request guard blocks all REST write operations (POST/PUT/PATCH/DELETE) and all GraphQL mutations except explicit user-confirmed PR approvals (`addPullRequestReview` with `event: APPROVE`). ### Local development OAuth App diff --git a/README.md b/README.md index f10df639..451108b0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Open issues where you're the creator, assignee, or mentioned. A scope filter let ### Pull Requests -Open PRs with CI status dots (green/yellow/red), review decision badges, size badges (XS–XL by lines changed), and draft indicators. A "blocked" filter catches PRs where checks are failing or a review requested changes. The scope filter works here too. Reviewer avatars stack for multiple reviewers. +Open PRs with CI status dots (green/yellow/red), review decision badges, a read-only `auto` badge when GitHub auto-merge is enabled (with merge method tooltip), size badges (XS–XL by lines changed), draft indicators, and a two-step inline `Approve` button on PR rows requiring approval. A "blocked" filter catches PRs where checks are failing or a review requested changes. The scope filter works here too. Reviewer avatars stack for multiple reviewers. ### Actions @@ -128,8 +128,8 @@ src/ layout/ # Header, TabBar, FilterBar onboarding/ # OnboardingWizard, OrgSelector, RepoSelector settings/ # SettingsPage, TrackedUsersSection, ThemePicker, Section, SettingRow - shared/ # 19 shared components: FilterInput, FilterChips, StatusDot, - # ReviewBadge, SizeBadge, RoleBadge, SortDropdown, PaginationControls, + shared/ # 28 shared components: FilterInput, FilterChips, StatusDot, + # ReviewBadge, AutoMergeBadge, SizeBadge, RoleBadge, SortDropdown, PaginationControls, # LoadingSpinner, SkeletonRows, ToastContainer, NotificationDrawer, # RepoLockControls, UserAvatarBadge, ExpandCollapseButtons, # RepoGitHubLink, ChevronIcon, ExternalLinkIcon, Tooltip/InfoTooltip @@ -170,7 +170,7 @@ pnpm run screenshot # Capture dashboard screenshot ## Security -OAuth tokens are stored in `localStorage` under an app-specific key — this is standard for single-user personal dashboards and matches the threat model here. CSP headers block script injection via Cloudflare (`script-src 'self'` with a SHA-256 exception for the dark-mode initialization script only). An Octokit hook blocks all non-GET requests except `POST /graphql` as a read-only guard — the `repo` scope is required for private repo access, but the app never performs writes. OAuth state is generated with `crypto.getRandomValues` and verified on callback. Token validation runs on every page load via `GET /user`; a 401 clears the stored token immediately. +OAuth tokens are stored in `localStorage` under an app-specific key — this is standard for single-user personal dashboards and matches the threat model here. CSP headers block script injection via Cloudflare (`script-src 'self'` with a SHA-256 exception for the dark-mode initialization script only). An Octokit hook blocks all non-GET REST requests and all GraphQL mutations except the single user-confirmed PR approval mutation (addPullRequestReview with event: APPROVE) — the repo scope is required for private repo access, and all other write operations are rejected client-side. OAuth state is generated with `crypto.getRandomValues` and verified on callback. Token validation runs on every page load via `GET /user`; a 401 clears the stored token immediately. ## Deployment diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 20e7a01d..5396eb23 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -81,7 +81,7 @@ If you prefer not to use OAuth, you can sign in with a GitHub Personal Access To Two token formats are accepted: - **Classic tokens** (starts with `ghp_`) — recommended. Works across all organizations you belong to. Required scopes: `repo`, `read:org` (under admin:org). -- **Fine-grained tokens** (starts with `github_pat_`) — also work, but only access one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read). +- **Fine-grained tokens** (starts with `github_pat_`) — also work, but only access one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read and write to approve PRs from the dashboard, or read-only for viewing only). The token is validated against the GitHub API before being stored. It is saved permanently in your browser's `localStorage` — you will not need to re-enter it on revisit. @@ -223,6 +223,18 @@ The dot links to the PR's checks page on GitHub. | Needs review | Review has been requested but not yet submitted | | Dismissed | Previously submitted review was dismissed | +#### Auto-Merge Badge + +When GitHub auto-merge is enabled on a pull request, a read-only `auto` badge appears next to the review badge (in both comfortable and compact density across the Pull Requests, Dependencies, and Tracked tabs). Hover or focus the badge to view the configured merge method (`merge`, `squash`, or `rebase`). + +#### Inline Approve Action + +Open, non-draft pull requests not authored by you show an **Approve** button in the right-side action slot (next to Pin and Ignore) when branch protection requires a review (`Review needed`) or when a review has been requested of you or your team (unless you have already approved the PR without a fresh re-request). + +Approval uses a two-step inline confirmation to prevent accidental clicks: +1. Click **Approve** once to arm confirmation (**Confirm?**, or **Confirm (auto)** when auto-merge is enabled on the PR). The confirmation state resets automatically after 4 seconds, on Escape, or when focus leaves the button. +2. Click **Confirm?** (or **Confirm (auto)**) to submit an `APPROVE` review bound to the PR's current head commit SHA (`commitOID`). If new commits were pushed since the last refresh, GitHub rejects the stale approval and the dashboard triggers a refresh. + #### Size Badges PR size is computed from total lines changed (additions + deletions): @@ -826,7 +838,11 @@ For detailed per-source API call counts, see Settings > API Usage. OAuth tokens (from "Sign in with GitHub") work across all your organizations and support all features. Classic PATs with the correct scopes (`repo`, `read:org`) behave identically to OAuth. -Fine-grained PATs are limited to one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read). +Fine-grained PATs are limited to one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read and write to approve PRs from the dashboard, or read-only for viewing only). + +**Approving a PR fails with a permission error (403 / FORBIDDEN).** + +Your token does not have write permission for pull requests. If you are using a fine-grained Personal Access Token, open GitHub Settings, edit or regenerate the token with **Pull requests** set to **Read and write** (`Pull requests: Read and write`), and replace your token in **Settings > Data > Authentication**. **Data looks stale after switching back to the tab.** diff --git a/src/app/pages/LoginPage.tsx b/src/app/pages/LoginPage.tsx index 6563f139..6dce0326 100644 --- a/src/app/pages/LoginPage.tsx +++ b/src/app/pages/LoginPage.tsx @@ -287,7 +287,7 @@ export default function LoginPage() { > Fine-grained tokens - {" "}also work, but only access one org at a time. Add read-only permissions for Actions, Contents, Issues, and Pull requests. + {" "}also work, but only access one org at a time. Add read-only permissions for Actions, Contents, and Issues, plus Read and write for Pull requests (or read-only if you don't approve PRs from the dashboard).

diff --git a/src/app/pages/PrivacyPage.tsx b/src/app/pages/PrivacyPage.tsx index 8ae75ccd..8e26b40a 100644 --- a/src/app/pages/PrivacyPage.tsx +++ b/src/app/pages/PrivacyPage.tsx @@ -194,9 +194,11 @@ export default function PrivacyPage() { GitHub API access

- The app accesses the GitHub API on your behalf using an OAuth token. - It reads your issues, pull requests, and workflow runs — nothing is - written. You can revoke access at any time from{" "} + The app accesses the GitHub API on your behalf using an OAuth token or + Personal Access Token. It reads your issues, pull requests, and workflow + runs, and only writes to GitHub when you explicitly click and confirm + Approve on a pull request. All other write operations are blocked + client-side. You can revoke access at any time from{" "} { screen.getByText(/only access one org at a time/i); }); + it("displays 'Read and write for Pull requests' in fine-grained token guidance", async () => { + const user = userEvent.setup(); + render(() => ); + await user.click(screen.getByText("Use a Personal Access Token")); + expect(screen.getByText(/Read and write for Pull requests/)).toBeTruthy(); + }); + it("clicking 'Use OAuth instead' returns to OAuth view and clears state", async () => { const user = userEvent.setup(); render(() => ); diff --git a/tests/components/dashboard/DependenciesTab.test.tsx b/tests/components/dashboard/DependenciesTab.test.tsx index 9fef0397..2d3dfc89 100644 --- a/tests/components/dashboard/DependenciesTab.test.tsx +++ b/tests/components/dashboard/DependenciesTab.test.tsx @@ -782,6 +782,87 @@ describe("DependenciesTab — unknown bot banner", () => { }); }); +// ── Auto-merge badge and inline Approve action ─────────────────────────────── + +describe("DependenciesTab — auto-merge badge and Approve action", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge in comfortable and compact density and preserves category badge first in DOM order", () => { + const prAuto = makeMergeablePR({ + id: 8001, + number: 801, + title: "Bump axios from 0.27.1 to 0.27.2", + autoMergeMethod: "SQUASH", + enriched: true, + }); + const prNoAuto = makeMergeablePR({ + id: 8002, + number: 802, + title: "Bump lodash from 4.16.0 to 4.17.0", + autoMergeMethod: null, + enriched: true, + }); + + const { unmount } = renderTab({ pullRequests: [prAuto, prNoAuto] }); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + + // Verify category badge ("patch") still comes before auto-merge badge in DOM order + const items = screen.getAllByRole("listitem"); + expect(items[0].querySelector(".badge")?.textContent?.trim()).toBe("patch"); + unmount(); + + updateConfig({ viewDensity: "compact" }); + renderTab({ pullRequests: [prAuto, prNoAuto] }); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("shows Approve button for eligible dependency PRs and invokes onApprovePR(pr) on confirmation", () => { + const onApprovePR = vi.fn(); + const eligibleDepPR = makeNeedsActionPR({ + id: 8010, + number: 810, + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8010", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + enriched: true, + }); + const alreadyApprovedDepPR = makeMergeablePR({ + id: 8011, + number: 811, + title: "Bump lodash from 4.16.0 to 4.17.0", + nodeId: "PR_kwDOdep8011", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + enriched: true, + }); + + renderTab({ + pullRequests: [eligibleDepPR, alreadyApprovedDepPR], + userLogin: "testuser", + onApprovePR, + }); + + const approveBtn = screen.getByLabelText(/^Approve #810 /); + expect(screen.queryByLabelText(/^Approve #811 /)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligibleDepPR); + }); +}); + // ── Ignore button ───────────────────────────────────────────────────────────── describe("DependenciesTab — ignore button", () => { From 6bd9d983971805684aa9b38a82251da0178b6bcd Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 08:55:32 -0400 Subject: [PATCH 6/8] fix(dashboard): address API and structural review findings --- .../components/dashboard/DashboardPage.tsx | 77 ++++++++----------- .../components/dashboard/DependenciesTab.tsx | 3 - src/app/components/dashboard/ItemRow.tsx | 10 +-- src/app/services/api.ts | 7 +- src/app/services/github.ts | 34 +++++--- src/shared/validation.ts | 1 - tests/components/DashboardPage.test.tsx | 47 +++++++++++ tests/components/ItemRow.test.tsx | 17 ++++ tests/services/github.test.ts | 6 ++ 9 files changed, 131 insertions(+), 71 deletions(-) diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index 96811238..79e04faf 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -328,9 +328,6 @@ async function pollFetch(): Promise { if (!regressing) { Object.assign(pr, pickEnrichmentFields(e)); pr.reviewDecision = e.reviewDecision; - pr.autoMergeMethod = e.autoMergeMethod; - pr.viewerReviewRequested = e.viewerReviewRequested; - pr.viewerLatestReviewState = e.viewerLatestReviewState; pr.enriched = e.enriched; } pr.nodeId = e.nodeId; @@ -340,6 +337,7 @@ async function pollFetch(): Promise { } } else { state.pullRequests = fallbackToPreviousEnrichment(state.pullRequests, data.pullRequests); + for (const pr of state.pullRequests) applyRecentApprovalGuard(pr, currentLogin); } })); } else { @@ -349,6 +347,7 @@ async function pollFetch(): Promise { // DOM updates are synchronous within the setter, so save/restore // around it to prevent scroll reset from DOM rebuild. const pullRequests = fallbackToPreviousEnrichment(dashboardData.pullRequests, data.pullRequests); + for (const pr of pullRequests) applyRecentApprovalGuard(pr, currentLogin); withScrollLock(() => { setDashboardData({ issues: data.issues, @@ -402,6 +401,25 @@ const [_coordinator, _setCoordinator] = createSignal void } | null>(null); const [_eventsCoordinator, _setEventsCoordinator] = createSignal<{ destroy: () => void } | null>(null); +function persistDashboardSnapshot(): void { + // Capture snapshot eagerly — a concurrent hot poll can mutate the store via produce + // between here and the deferred setTimeout write. + const snapshot = { + _v: CACHE_VERSION, + issues: [...dashboardData.issues], + pullRequests: [...dashboardData.pullRequests], + workflowRuns: [...dashboardData.workflowRuns], + lastRefreshedAt: dashboardData.lastRefreshedAt?.toISOString() ?? null, + }; + setTimeout(() => { + try { + localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); + } catch { + // Non-fatal + } + }, 0); +} + // Mutates data.issues[].surfacedBy and data.pullRequests[].surfacedBy in-place before merging. function handleTargetedData(data: DashboardData, affectedRepos: string[]): void { const affectedSet = new Set(affectedRepos.map(r => r.toLowerCase())); @@ -414,7 +432,9 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void } } const oldSurfacedByPRs = new Map(); + const existingPRById = new Map(); for (const pr of dashboardData.pullRequests) { + existingPRById.set(pr.id, pr); if (affectedSet.has(pr.repoFullName.toLowerCase()) && pr.surfacedBy?.length) { oldSurfacedByPRs.set(pr.id, pr.surfacedBy); } @@ -427,12 +447,18 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void item.surfacedBy = [...new Set([...(item.surfacedBy ?? []), ...oldSb])]; } } + const currentLogin = user()?.login ?? ""; for (const pr of data.pullRequests) { const oldSb = oldSurfacedByPRs.get(pr.id); if (oldSb) { pr.surfacedBy = [...new Set([...(pr.surfacedBy ?? []), ...oldSb])]; } - applyRecentApprovalGuard(pr, user()?.login ?? ""); + const existingPr = existingPRById.get(pr.id); + if (existingPr && pr.enriched === false && existingPr.enriched !== false) { + Object.assign(pr, pickEnrichmentFields(existingPr)); + pr.enriched = existingPr.enriched; + } + applyRecentApprovalGuard(pr, currentLogin); } withScrollLock(() => { @@ -474,24 +500,7 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void dispatchNotifications(newItems, config); seedHotSetsFromTargeted(data); - - // Capture snapshot eagerly — a concurrent hot poll can mutate the store via produce - // between here and the deferred setTimeout write. - const lastRefreshed = dashboardData.lastRefreshedAt; - const snapshot = { - _v: CACHE_VERSION, - issues: [...dashboardData.issues], - pullRequests: [...dashboardData.pullRequests], - workflowRuns: [...dashboardData.workflowRuns], - lastRefreshedAt: lastRefreshed?.toISOString() ?? null, - }; - setTimeout(() => { - try { - localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); - } catch { - // Non-fatal - } - }, 0); + persistDashboardSnapshot(); } export default function DashboardPage() { @@ -1469,14 +1478,7 @@ export default function DashboardPage() { setDashboardData( produce((state) => { const target = state.pullRequests.find((item) => item.id === pr.id); - if (!target) return; - target.viewerLatestReviewState = "APPROVED"; - target.viewerReviewRequested = false; - target.reviewDecision = nextDecision; - const loginLower = currentLogin.toLowerCase(); - if (loginLower && !target.reviewerLogins.some((r) => r.toLowerCase() === loginLower)) { - target.reviewerLogins = [...target.reviewerLogins, loginLower]; - } + if (target) applyRecentApprovalGuard(target, currentLogin); }) ); @@ -1490,20 +1492,7 @@ export default function DashboardPage() { errors: [], }); - const snapshot = { - _v: CACHE_VERSION, - issues: [...dashboardData.issues], - pullRequests: [...dashboardData.pullRequests], - workflowRuns: [...dashboardData.workflowRuns], - lastRefreshedAt: dashboardData.lastRefreshedAt?.toISOString() ?? null, - }; - setTimeout(() => { - try { - localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); - } catch { - // Non-fatal - } - }, 0); + persistDashboardSnapshot(); pushNotification(`approve-pr:${pr.id}`, `Approved ${pr.repoFullName}#${pr.number}`, "info"); } catch (err) { diff --git a/src/app/components/dashboard/DependenciesTab.tsx b/src/app/components/dashboard/DependenciesTab.tsx index b1487975..b1ddd204 100644 --- a/src/app/components/dashboard/DependenciesTab.tsx +++ b/src/app/components/dashboard/DependenciesTab.tsx @@ -464,9 +464,6 @@ function StatusGroup(props: StatusGroupProps) {

- - - diff --git a/src/app/components/dashboard/ItemRow.tsx b/src/app/components/dashboard/ItemRow.tsx index a8d3bbe8..726d0846 100644 --- a/src/app/components/dashboard/ItemRow.tsx +++ b/src/app/components/dashboard/ItemRow.tsx @@ -1,4 +1,4 @@ -import { createEffect, createMemo, createSignal, For, JSX, onCleanup, Show } from "solid-js"; +import { createEffect, createMemo, createSignal, For, JSX, on, onCleanup, Show } from "solid-js"; import { config } from "../../stores/config"; import { isSafeGitHubUrl } from "../../lib/url"; import { relativeTime, shortRelativeTime, formatCount } from "../../lib/format"; @@ -57,11 +57,9 @@ export default function ItemRow(props: ItemRowProps) { setConfirmingApprove(false); } - createEffect(() => { - if (!props.onApprove || props.isApproving) { - resetApproveConfirm(); - } - }); + createEffect( + on([() => props.onApprove, () => props.approveAutoMerge, () => props.isApproving], resetApproveConfirm, { defer: true }), + ); onCleanup(() => { clearApproveTimer(); diff --git a/src/app/services/api.ts b/src/app/services/api.ts index 755fc300..0dff561d 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -1418,14 +1418,13 @@ function mergeEnrichment( forkInfoMap.set(pr.id, e.headRepository); } - const viewerLatestReviewState = e.viewerLatestReviewState; const viewerReviewRequested = - viewerLatestReviewState === "APPROVED" && !e.viewerReviewRequested + e.viewerLatestReviewState === "APPROVED" && !e.viewerReviewRequested ? false : Boolean(pr.viewerReviewRequested || e.viewerReviewRequested); const reviewerLogins = viewerLogin && - (viewerReviewRequested || viewerLatestReviewState !== null) && + (viewerReviewRequested || e.viewerLatestReviewState !== null) && !e.reviewerLogins.includes(viewerLogin) ? [...e.reviewerLogins, viewerLogin] : e.reviewerLogins; @@ -1434,9 +1433,7 @@ function mergeEnrichment( ...pr, ...pickEnrichmentFields(e), reviewerLogins, - autoMergeMethod: e.autoMergeMethod, viewerReviewRequested, - viewerLatestReviewState, enriched: true, }; }); diff --git a/src/app/services/github.ts b/src/app/services/github.ts index 3d02c24f..49607935 100644 --- a/src/app/services/github.ts +++ b/src/app/services/github.ts @@ -96,6 +96,22 @@ export function updateRateLimitFromHeaders(headers: Record): voi } } +function updateGraphqlRateLimitFromHeaders(headers: Record): void { + const remaining = headers["x-ratelimit-remaining"]; + const reset = headers["x-ratelimit-reset"]; + const limit = headers["x-ratelimit-limit"]; + if (remaining !== undefined && reset !== undefined) { + const parsedRemaining = parseInt(remaining, 10); + const parsedReset = parseInt(reset, 10); + if (!Number.isFinite(parsedReset)) return; + _setGraphqlRateLimit({ + limit: safePositiveNumber(limit !== undefined ? parseInt(limit, 10) : NaN, _graphqlRateLimit()?.limit ?? 5000), + remaining: Number.isFinite(parsedRemaining) ? parsedRemaining : 0, + resetAt: new Date(parsedReset * 1000), + }); + } +} + // ── API request tracking callback ──────────────────────────────────────────── export interface ApiRequestInfo { @@ -209,16 +225,7 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { if (errHeaders) { try { if (isGraphql) { - const remaining = errHeaders["x-ratelimit-remaining"]; - const reset = errHeaders["x-ratelimit-reset"]; - const limit = errHeaders["x-ratelimit-limit"]; - if (remaining !== undefined && reset !== undefined) { - _setGraphqlRateLimit({ - limit: safePositiveNumber(limit !== undefined ? parseInt(limit, 10) : NaN, _graphqlRateLimit()?.limit ?? 5000), - remaining: Number.isFinite(parseInt(remaining, 10)) ? parseInt(remaining, 10) : 0, - resetAt: new Date(parseInt(reset, 10) * 1000), - }); - } + updateGraphqlRateLimitFromHeaders(errHeaders); } else { updateRateLimitFromHeaders(errHeaders); } @@ -231,9 +238,10 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { const headers = (response.headers ?? {}) as Record; const resetHeader = headers["x-ratelimit-reset"]; const resetEpochMs = resetHeader ? parseInt(resetHeader, 10) * 1000 : null; - const graphqlCost = isGraphql - ? (response.data as { data?: { rateLimit?: { cost?: number } } })?.data?.rateLimit?.cost ?? undefined + const bodyRateLimit = isGraphql + ? (response.data as { data?: { rateLimit?: { cost?: number } } })?.data?.rateLimit : undefined; + const graphqlCost = bodyRateLimit?.cost ?? undefined; const info: ApiRequestInfo = { url: options.url, method, status, isGraphql, apiSource, resetEpochMs, graphqlCost, }; @@ -241,6 +249,8 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { if (response.headers && !isGraphql) { updateRateLimitFromHeaders(response.headers as Record); + } else if (isGraphql && !bodyRateLimit) { + updateGraphqlRateLimitFromHeaders(headers); } return response; diff --git a/src/shared/validation.ts b/src/shared/validation.ts index e0c976a9..8d28388f 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -19,7 +19,6 @@ export const APPROVE_PR_MUTATION = ` } } } - rateLimit { cost limit remaining resetAt } } `.trim(); diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index 3dcfcad3..f44429c9 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -2038,6 +2038,53 @@ describe("DashboardPage — events poll targeted merge", () => { expect(vi.mocked(pollService.rebuildHotSets)).not.toHaveBeenCalled(); expect(vi.mocked(pollService.seedHotSetsFromTargeted)).toHaveBeenCalledWith(targetedData); }); + + it("preserves prior enrichment in handleTargetedData when targeted PR arrives with enriched: false", async () => { + const enrichedPR = makePullRequest({ + id: 61, + repoFullName: "org/repo", + enriched: true, + autoMergeMethod: "SQUASH", + viewerReviewRequested: true, + viewerLatestReviewState: "CHANGES_REQUESTED", + checkStatus: "success", + headSha: "1111111111111111111111111111111111111111", + }); + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [enrichedPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await waitFor(() => expect(capturedOnTargetedData).not.toBeNull()); + + const unenrichedTargetedPR = makePullRequest({ + id: 61, + repoFullName: "org/repo", + enriched: false, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, + checkStatus: null, + headSha: "", + }); + const targetedData: DashboardData = { + issues: [], + pullRequests: [unenrichedTargetedPR], + workflowRuns: [], + errors: [], + }; + capturedOnTargetedData?.(targetedData, ["org/repo"]); + + expect(unenrichedTargetedPR.enriched).toBe(true); + expect(unenrichedTargetedPR.autoMergeMethod).toBe("SQUASH"); + expect(unenrichedTargetedPR.viewerReviewRequested).toBe(true); + expect(unenrichedTargetedPR.viewerLatestReviewState).toBe("CHANGES_REQUESTED"); + expect(unenrichedTargetedPR.checkStatus).toBe("success"); + expect(unenrichedTargetedPR.headSha).toBe("1111111111111111111111111111111111111111"); + }); }); describe("DashboardPage — dependency pre-exclusivity", () => { diff --git a/tests/components/ItemRow.test.tsx b/tests/components/ItemRow.test.tsx index 741cc6bd..59688853 100644 --- a/tests/components/ItemRow.test.tsx +++ b/tests/components/ItemRow.test.tsx @@ -572,5 +572,22 @@ describe("ItemRow", () => { fireEvent.click(btn); expect(onApprove).not.toHaveBeenCalled(); }); + + it("resets 'Confirm?' back to 'Approve' when onApprove prop reference changes (e.g. headSha updated on poll)", () => { + const onApproveA = vi.fn(); + const onApproveB = vi.fn(); + const [approveFn, setApproveFn] = createSignal<() => void>(onApproveA); + + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + setApproveFn(() => onApproveB); + expect(btn.textContent).toContain("Approve"); + expect(onApproveA).not.toHaveBeenCalled(); + expect(onApproveB).not.toHaveBeenCalled(); + }); }); }); diff --git a/tests/services/github.test.ts b/tests/services/github.test.ts index ba00b185..d8a76f3c 100644 --- a/tests/services/github.test.ts +++ b/tests/services/github.test.ts @@ -127,6 +127,7 @@ describe("createGitHubClient", () => { expect(GITHUB_NODE_ID_RE.test("PR_kwDOtest42")).toBe(true); expect(GITHUB_NODE_ID_RE.test("MDExOlB1bGxSZXF1ZXN0NDI=")).toBe(true); expect(GIT_SHA_RE.test(validSha)).toBe(true); + expect(APPROVE_PR_MUTATION).not.toContain("rateLimit"); vi.unstubAllGlobals(); }); @@ -803,6 +804,11 @@ describe("hook.wrap — rate limit signal routing", () => { // _coreRateLimit must remain at seeded value — GraphQL success must not contaminate it const rl = getCoreRateLimit(); expect(rl!.remaining).toBe(1234); + + // Because the response had no body rateLimit (as on GraphQL mutations), _graphqlRateLimit updates from headers + const graphqlRl = getGraphqlRateLimit(); + expect(graphqlRl).not.toBeNull(); + expect(graphqlRl!.remaining).toBe(9999); }); it("successful REST request updates _coreRateLimit but NOT _graphqlRateLimit", async () => { From 8f065a7adc6355d1af005d3118cc3c480e6a6481 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 20 Oct 2026 11:34:14 -0400 Subject: [PATCH 7/8] fix(dashboard): address PR #163 review findings and expand test coverage --- mcp/src/octokit.ts | 12 +- .../components/dashboard/DashboardPage.tsx | 104 +-- src/app/components/dashboard/ItemRow.tsx | 68 +- src/app/services/github.ts | 11 +- src/shared/validation.ts | 11 + tests/components/DashboardPage.test.tsx | 647 ++++++++++++++++++ tests/components/ItemRow.test.tsx | 23 + .../dashboard/DashboardPage.test.tsx | 112 +-- tests/services/api-optimization.test.ts | 43 ++ tests/shared/validation.test.ts | 40 +- 10 files changed, 884 insertions(+), 187 deletions(-) diff --git a/mcp/src/octokit.ts b/mcp/src/octokit.ts index 5b73bb34..6059ae2a 100644 --- a/mcp/src/octokit.ts +++ b/mcp/src/octokit.ts @@ -2,6 +2,7 @@ import { Octokit } from "@octokit/core"; import { throttling } from "@octokit/plugin-throttling"; import { retry } from "@octokit/plugin-retry"; import { paginateRest } from "@octokit/plugin-paginate-rest"; +import { isReadOnlyGraphqlQuery } from "../../src/shared/validation.js"; // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -11,17 +12,6 @@ type GitHubOctokitInstance = InstanceType; // ── Client factory ─────────────────────────────────────────────────────────── -function isReadOnlyGraphqlQuery(query: unknown): boolean { - if (typeof query !== "string") return false; - // Strip block strings, single-line strings, and # comments in a single left-to-right pass - const sanitized = query - .replace(/"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|#[^\r\n]*/g, (m) => (m.startsWith("#") ? "" : '""')) - .trim(); - if (!sanitized) return false; - if (!/^(?:query\b|\{)/i.test(sanitized)) return false; - return !/\b(?:mutation|subscription)\b/i.test(sanitized); -} - export function createOctokitClient(token: string): GitHubOctokitInstance { const client = new GitHubOctokit({ auth: token, diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index 79e04faf..09a5be5f 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -16,7 +16,7 @@ import { isRepoExcludedFromDependencies } from "../../lib/dependency-exclusion"; import { findDashboardIssues, parseAbandonedSection, resetAbandonedPatternCache, type AbandonedDependency } from "../../lib/dependency-dashboard"; import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields, approvePullRequest } from "../../services/api"; import type { SortOption } from "../shared/SortDropdown"; -import type { Issue, PullRequest, WorkflowRun } from "../../services/api"; +import type { Issue, PullRequest, WorkflowRun, HotPRStatusUpdate } from "../../services/api"; import { fetchOrgs } from "../../services/api"; import { createPollCoordinator, @@ -211,6 +211,54 @@ function applyRecentApprovalGuard(pr: PullRequest, currentLogin: string): void { } } +export function applyHotPollPRUpdates( + state: { pullRequests: PullRequest[] }, + prUpdates: ReadonlyMap, + currentLogin = "" +): Set { + const terminalPrIds = new Set(); + for (const [prId, update] of prUpdates) { + const s = update.state; + if (s === "CLOSED" || s === "MERGED") terminalPrIds.add(prId); + } + const loginLower = currentLogin.toLowerCase(); + for (const pr of state.pullRequests) { + const update = prUpdates.get(pr.id); + if (!update) continue; + pr.state = update.state; // detect closed/merged quickly + pr.checkStatus = update.checkStatus; + pr.reviewDecision = update.reviewDecision; + if (update.headSha) { + pr.headSha = update.headSha; + } + if (update.autoMergeMethod !== undefined) { + pr.autoMergeMethod = update.autoMergeMethod; + } + if (update.viewerLatestReviewState !== undefined) { + pr.viewerLatestReviewState = update.viewerLatestReviewState; + } + if (update.viewerReviewRequested !== undefined) { + if (update.viewerReviewRequested) { + pr.viewerReviewRequested = true; + } else if (update.viewerLatestReviewState === "APPROVED") { + pr.viewerReviewRequested = false; + } + } + if ( + loginLower && + (pr.viewerReviewRequested || pr.viewerLatestReviewState != null) && + !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower) + ) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } + applyRecentApprovalGuard(pr, currentLogin); + } + if (terminalPrIds.size > 0) { + state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); + } + return terminalPrIds; +} + // Skip retrying a dep-PR body fetch that errored/timed out on its last attempt until // this cooldown elapses — prevents burning a full GRAPHQL_BODY_FETCH_TIMEOUT_MS timeout, // an undeduped Sentry event, and a repeated user notification every poll cycle for as @@ -790,46 +838,10 @@ export default function DashboardPage() { // If a full refresh completed during the fetch, _hotPollGeneration will have // been incremented by rebuildHotSets(), and fetchGeneration will be stale. if (fetchGeneration !== getHotPollGeneration()) return; // stale, discard - const terminalPrIds = new Set(); - for (const [prId, update] of prUpdates) { - const s = update.state; - if (s === "CLOSED" || s === "MERGED") terminalPrIds.add(prId); - } + let terminalPrIds = new Set(); setDashboardData(produce((state) => { const currentLogin = user()?.login ?? ""; - const loginLower = currentLogin.toLowerCase(); - // Apply PR status updates - for (const pr of state.pullRequests) { - const update = prUpdates.get(pr.id); - if (!update) continue; - pr.state = update.state; // detect closed/merged quickly - pr.checkStatus = update.checkStatus; - pr.reviewDecision = update.reviewDecision; - if (update.headSha) { - pr.headSha = update.headSha; - } - if (update.autoMergeMethod !== undefined) { - pr.autoMergeMethod = update.autoMergeMethod; - } - if (update.viewerLatestReviewState !== undefined) { - pr.viewerLatestReviewState = update.viewerLatestReviewState; - } - if (update.viewerReviewRequested !== undefined) { - if (update.viewerReviewRequested) { - pr.viewerReviewRequested = true; - } else if (update.viewerLatestReviewState === "APPROVED") { - pr.viewerReviewRequested = false; - } - } - if ( - loginLower && - (pr.viewerReviewRequested || pr.viewerLatestReviewState != null) && - !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower) - ) { - pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; - } - applyRecentApprovalGuard(pr, currentLogin); - } + terminalPrIds = applyHotPollPRUpdates(state, prUpdates, currentLogin); // Apply workflow run updates for (const run of state.workflowRuns) { const update = runUpdates.get(run.id); @@ -839,9 +851,6 @@ export default function DashboardPage() { run.updatedAt = update.updatedAt; run.completedAt = update.completedAt; } - if (terminalPrIds.size > 0) { - state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); - } })); if (terminalPrIds.size > 0) { console.info(`[hot-poll] Spliced ${terminalPrIds.size} terminal PR(s) from store`); @@ -1451,6 +1460,9 @@ export default function DashboardPage() { if (approvingPRIds().has(pr.id)) return; const client = getClient(); if (!client || !pr.nodeId || !pr.headSha) return; + const nodeId = pr.nodeId; + const approvedHeadSha = pr.headSha; + const priorReviewDecision = pr.reviewDecision; // Clear any prior notification for this PR so a retry with the same error message // is not suppressed by pushNotification's same-message no-op guard. @@ -1463,14 +1475,14 @@ export default function DashboardPage() { }); try { - const result = await approvePullRequest(client, pr.nodeId, pr.headSha); + const result = await approvePullRequest(client, nodeId, approvedHeadSha); if (getClient() !== client) return; const nextDecision: PullRequest["reviewDecision"] = - result.reviewDecision ?? (pr.reviewDecision === "REVIEW_REQUIRED" ? "APPROVED" : pr.reviewDecision); + result.reviewDecision ?? (priorReviewDecision === "REVIEW_REQUIRED" ? "APPROVED" : priorReviewDecision); recentlyApprovedPRs.set(pr.id, { - headSha: pr.headSha, + headSha: approvedHeadSha, reviewDecision: nextDecision, approvedAt: Date.now(), }); @@ -1487,7 +1499,7 @@ export default function DashboardPage() { // even when checkStatus was already "success" prior to approval. seedHotSetsFromTargeted({ issues: [], - pullRequests: [{ ...pr, enriched: true, checkStatus: "pending" }], + pullRequests: [{ ...pr, nodeId, headSha: approvedHeadSha, enriched: true, checkStatus: "pending" }], workflowRuns: [], errors: [], }); diff --git a/src/app/components/dashboard/ItemRow.tsx b/src/app/components/dashboard/ItemRow.tsx index 726d0846..9e30fd8b 100644 --- a/src/app/components/dashboard/ItemRow.tsx +++ b/src/app/components/dashboard/ItemRow.tsx @@ -57,8 +57,19 @@ export default function ItemRow(props: ItemRowProps) { setConfirmingApprove(false); } + const isApproving = createMemo(() => Boolean(props.isApproving)); + const approveAutoMerge = createMemo(() => Boolean(props.approveAutoMerge)); + createEffect( - on([() => props.onApprove, () => props.approveAutoMerge, () => props.isApproving], resetApproveConfirm, { defer: true }), + on( + [() => props.onApprove, approveAutoMerge, isApproving], + (curr, prev) => { + if (!prev || curr.some((v, i) => v !== prev[i])) { + resetApproveConfirm(); + } + }, + { defer: true }, + ), ); onCleanup(() => { @@ -141,6 +152,33 @@ export default function ItemRow(props: ItemRowProps) { return slash >= 0 ? props.repo.slice(slash + 1) : props.repo; }); + const approveButtonMeta = createMemo(() => { + if (props.isApproving) { + return { + tooltip: "Submitting approval...", + buttonClass: "btn-ghost opacity-100", + ariaLabel: `Approving #${props.number} ${props.title}`, + }; + } + if (confirmingApprove()) { + return { + tooltip: props.approveAutoMerge + ? "Click again to confirm approval (auto-merge enabled)" + : "Click again to confirm approval", + buttonClass: "btn-warning opacity-100", + ariaLabel: props.approveAutoMerge + ? `Confirm approve #${props.number} ${props.title} (auto-merge enabled)` + : `Confirm approve #${props.number} ${props.title}`, + }; + } + return { + tooltip: "Approve this pull request", + buttonClass: + "btn-ghost text-success hover:bg-success/15 opacity-0 group-hover:opacity-100 focus-visible:opacity-100", + ariaLabel: `Approve #${props.number} ${props.title}`, + }; + }); + return (
+ + + ); + return (
{props.titlePrefix}
- {/* Title — truncated, fills available space */} - - {props.title} - + {/* Title + inline hover Approve button — fills available space */} +
+ + {props.title} + + {renderApproveButton()} +
{/* Children (badges) inline */} @@ -314,9 +359,12 @@ export default function ItemRow(props: ItemRowProps) {
{props.titlePrefix}
- - {props.title} - +
+ + {props.title} + + {renderApproveButton()} +
{/* Labels row */} @@ -392,44 +440,6 @@ export default function ItemRow(props: ItemRowProps) {
- {/* Approve button — two-step inline confirmation for eligible PRs */} - - - - - - {/* Pin button — visible on hover, always visible when tracked */} diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index 81bfc655..969e9ec9 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -3598,7 +3598,7 @@ describe("DashboardPage — Jira expiration UX and reactive re-authentication", describe("DashboardPage — PR approval integration", () => { const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; - it("completes two-step PR approval flow, updates badge to Approved, seeds hot sets, and pushes info notification", async () => { + it("completes two-step PR approval flow, updates badge to Approved, seeds hot sets, and does not push a persistent notification on success", async () => { const user = userEvent.setup(); const graphqlMock = vi.fn().mockResolvedValue({ addPullRequestReview: { @@ -3684,12 +3684,7 @@ describe("DashboardPage — PR approval integration", () => { expect(screen.queryByText("Review needed")).toBeNull(); }); expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); - - expect(errorsLib.pushNotification).toHaveBeenCalledWith( - "approve-pr:42", - "Approved owner/repo#42", - "info" - ); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); }); it("handles 403 / FORBIDDEN error without calling expireToken, leaves PR unapproved, re-enables Approve button, and pushes PAT write permission error", async () => { @@ -4066,7 +4061,7 @@ describe("DashboardPage — PR approval integration", () => { }); await waitFor(() => { - expect(errorsLib.pushNotification).toHaveBeenCalledWith("approve-pr:42", "Approved owner/repo#42", "info"); + expect(pollService.seedHotSetsFromTargeted).toHaveBeenCalledOnce(); }); // Because headSha changed to newSha while validSha was being approved, the guard evicts the entry diff --git a/tests/components/ItemRow.test.tsx b/tests/components/ItemRow.test.tsx index b37c7f91..92a823ea 100644 --- a/tests/components/ItemRow.test.tsx +++ b/tests/components/ItemRow.test.tsx @@ -612,5 +612,20 @@ describe("ItemRow", () => { setApprovingSet(new Set()); expect(btn.textContent).toBe("Confirm?"); }); + + it("renders right after the title and collapses width (max-w-0) when idle so non-hovered rows have no blank space", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + const wrapper = btn.parentElement!; + expect(wrapper.previousElementSibling?.textContent).toBe("Fix a bug"); + expect(wrapper.className).toContain("max-w-0"); + expect(wrapper.className).toContain("group-hover:max-w-40"); + + fireEvent.click(btn); + expect(wrapper.className).toContain("max-w-40"); + expect(wrapper.className).not.toContain("max-w-0"); + }); }); });